«
C++随机数应用实例代码
点亮灯 发布于
阅读:188
C++
//随机生成十个10以内的加法题,每行两题.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
int shu1;
int shu2;
srand(time(0)) ;
for (int i=1;i<=10;i++){
shu1=rand()%(9-0+1)+0 ;
shu2=rand()%(9-0+1)+0 ;
cout<<shu1<<"+"<<shu2<<"=\t" ;
if (i%2==0){
cout<<endl;
}
}
}
//随机生成十个10以内的加法题,每行两题.
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
// 初始化随机数种子
std::srand(std::time(0));
// 生成10道加法题
for (int i = 1; i <= 10; i++) {
// 生成两个10以内的随机数
int num1 = std::rand() % 10 + 1; // 1-10
int num2 = std::rand() % 10 + 1; // 1-10
// 输出题目
std::cout << num1 << " + " << num2 << " = \t";
// 每两题换一行
if (i % 2 == 0) {
std::cout << std::endl;
}
}
return 0;
}
//随机生成十个10以内的加法题,每行两题.
#include <iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
//定义变量
int shu1;
int shu2;
int jishu;
//计算输出
srand(time(0));
for(jishu=1;jishu<11;jishu++)
{
shu1=rand()%(9-0+1)+0;
shu2=rand()%(9-0+1)+0;
cout<<shu1<<"+"<<shu2<<"=\t";
if(jishu%2==0)
{
cout<<endl;
}
}
}
//自动输出1000以内的随机数一个,按 1继续输出
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main(){
//准备变量
int shujishu;
int jixu;
//计算输出
srand(time(0));
do {
shujishu=rand()%(1000-1+1)+1;
cout<<"随机数是:"<<shujishu<<endl;
cout<<endl;
cout<<"按'1'继续输出随机数\t" ;
cin>>jixu;
cout<<endl;
} while(jixu==1);
}
#include<iostream> //引入iostream库,才能使用输入输出流,cin和cout
#include<cstdlib> //工具函数,包括内存管理、随机数生成、程序控制等
#include<ctime> //提供与时间相关的函数和类型
using namespace std; //引入 std 命名空间
int main()
{
//1,准备变最
int shu1;
int shu2;
int he;
//2,录入数据
srand(time(0)); //获取当前时间(从1970年1月1日至今的秒数)作为初始化随机数种子,这样每次程序运行时都会产生不同的随机数.
shu1 = rand()%(99-10+1)+10;
shu2 = rand()%(99-10+1)+10;
cout<<"一道两位数加法测试题,请测试"<<endl;
cout<<shu1<<"+"<<shu2<<"=";
cin>>he;
// 3,计算shu1和shu2的和,
if(he==shu1+shu2)
{
cout<<"恭喜您,答对了!"<<endl;
}
else
{
cout<<"你答错了"<<endl;
}
}