題目:四則運算出題器。
思路:利用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<<"~~~~~~~~~~~~~~~~~~"<<"請您理性留作業!"<<"~~~~~~~~~~~~~~~~~"<<"\n";
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)<<"="<<"\n";
break;
case 1:
cout<<j+1<<":"<<" "<<num(1)<<"-"<<num(2)<<"="<<"\n";
break;
case 2:
cout<<j+1<<":"<<" "<<num(1)<<"*"<<num(2)<<"="<<"\n";
break;
case 3:
n=num(2);
if(n!=0)
{
cout<<j+1<<":"<<" "<<num(1)<<"/"<<n<<"="<<"\n";
}
else
{
j--;
}
break;
}
}
break;
}
}
return 0;
}