四则运算1
四则运算 支持整数和真分数
1 #include <iostream> 2 #include <ctime> 3 #include <cstdlib> 4 #include <string> 5 #include <iomanip> 6 #include <sstream> 7 using namespace std; 8 9 bool isTrueFraction(int numerator,int denominator) //判断产生的分数是否是真分数 10 { 11 if(numerator >= denominator) 12 return false; 13 14 for(int i = 2 ; i <= numerator ; i++) //判断分数是否能够约分 15 { 16 if(numerator % i ==0 && denominator % i ==0) 17 return false; 18 } 19 20 return true; 21 } 22 23 string getNum() 24 { 25 int n = rand(); 26 if(n%7 == 0) //若随机数n是7的倍数,产生一个真分数和一个整数,否则为两个整数 27 { 28 int num1 = rand() % 100; 29 int num2 = rand() % 100; 30 int num3 = rand() % 100; 31 // cout << num1 <<"+"<<num2<<"+"<<num3<<endl; 32 if(isTrueFraction(num1,num2)) 33 { 34 stringstream s1,s2,s3; 35 string ss1,ss2,ss3; 36 s1<<num1; 37 s1>>ss1; 38 s2<<num2; 39 s2>>ss2; 40 s3<<num3; 41 s3>>ss3; 42 return ss1+"/"+ss2+","+ss3; 43 }else 44 { 45 return getNum(); 46 } 47 }else 48 { 49 int num1 = rand() % 100; 50 int num2 = rand() % 100; 51 //cout << num1 <<"+"<<num2<<endl; 52 stringstream s1,s2; 53 string ss1,ss2; 54 s1<<num1; 55 s1>>ss1; 56 s2<<num2; 57 s2>>ss2; 58 return ss1+","+ss2; 59 } 60 } 61 62 char getOperator(string num2) 63 { 64 char a[] = {'+','-','*','/'}; 65 if(num2 == "0") 66 return a[rand() % 3]; 67 else 68 return a[rand() % 4]; 69 70 } 71 72 73 int main(int argc, char *argv[]) 74 { 75 srand((int)time(0)); 76 77 for(int i = 0; i < 30 ; i++){ 78 string num = getNum(); 79 string num1 = num.substr(0,num.find(",")); //由逗号分割, 80 string num2 = num.substr(num.find(",")+1); 81 char op = getOperator(num2); 82 cout <<left << setw(4) << i+1 << setw(5)<<num1 <<setw(2)<<op<<setw(5)<<num2 <<endl; 83 } 84 85 return 0; 86 }
首先 getNum()获得两个数,并用逗号分隔的字符串格式返回,通过string::find()和string::substr()分别获得两个运算数,
然后 通过getOperator()获得运算符,并以第二个数作为参数,如果第二个数为0,那么不能取除法,
最后 附上运行截图。