题目:四则运算出题器。
思路:利用rand()%100函数生成100以内的随机正整数,同样利用随机函数rand()%4可以随机生成0,1,2,3分别对应加减乘除的四种情况的随机整数。这个程序对题目进行了编号,可以自定义题目的数量,自动去除除数为0的不合法情况。
代码:
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
int num(int x)
{
return rand()%100;
}
int fh()
{
return rand()%4;
}
int main()
{
int a,i,j,n;
cout<<"~~~~~~~~~~~~~~~~~~"<<"请您理性留作业!"<<"~~~~~~~~~~~~~~~~~"<<"
";
cout<<"请输入题目数量:";
cin>>a;
srand(time(NULL));
while(1)
{
if(a<1)
{
cout<<"输入有误,请重新输入:";
cin>>a;
}
else
{
for(j=0;j<a;j++)
{
i=fh();
switch(i)
{
case 0:
cout<<j+1<<":"<<" "<<num(1)<<"+"<<num(2)<<"="<<"
";
break;
case 1:
cout<<j+1<<":"<<" "<<num(1)<<"-"<<num(2)<<"="<<"
";
break;
case 2:
cout<<j+1<<":"<<" "<<num(1)<<"*"<<num(2)<<"="<<"
";
break;
case 3:
n=num(2);
if(n!=0)
{
cout<<j+1<<":"<<" "<<num(1)<<"/"<<n<<"="<<"
";
}
else
{
j--;
}
break;
}
}
break;
}
}
return 0;
}
运行截图
总结
用C++编的小程序。忘记了rand函数的用法,百度上学习了一下。