我创建了一个模块化计算器,用于执行一系列数学运算,最后对之前的所有内容取模。但是,我一直得到错误的结果。
#include <iostream>
using namespace std;
int main(){
int num1, num2, ans = 0;
char oper = ' ';
cin >> num1>> oper >> num2;
//The first time
if (oper == '*')
ans =num1*num2;
else if (oper == '+')
ans = num1+num2;
//other times
do {
cin>> oper >> num2;
if (oper == '*')
ans =ans*num2;
else if (oper == '+')
ans = ans+num2;
} while (oper!='%');
if (oper == '%')
ans = (ans % num2);
cout<<ans;
}
输入:
4
* 8805
* 99
* 12
+ 6
+ 367
* 575
+ 66
+ 9
* 8
* 8
* 711
+ 130
* 5
+ 5
+ 1
+ 73
* 811
* 33
+ 56
+ 80
* 350
* 116
+ 179
* 383
* 12
+ 59
+ 5150
* 10
+ 5
+ 8783
* 48
* 84
* 7
+ 390
+ 7057
* 10
+ 8366
+ 8856
* 99
* 9
+ 3019
+ 228
* 334
+ 75
+ 6353
+ 7151
* 8
% 1408
输出:-1240
预期:808
有什么解释吗? (BigInt
或 double
或 unsigned int
而不是 int
似乎没有解决任何问题;我已经尝试了所有那些)。
最佳答案
由于 int 溢出,您得到了错误的答案。
让我们举个例子
假设您的输入如下所示
4
* 432
* 422
* 432
% 8
你的程序会给出错误的答案,因为
第一次输入后,ans = 4 * 432 = 1728
第二次输入后,ans = 1732 * 432 = 746496(大于int最高范围,发生int溢出,给你错误答案)
为此,我们可以使用下面的模运算公式来避免 int 溢出。
- (A + B) % R = (A % R + B % R) % R
- (A * B) % R = (A % R * B % R) % R
供您引用, (26+3*2)%3 = (26%3 + 3%3 * 2%3) %3
试试这个
#include <iostream>
#define MAX 100 // guess at most 100 lines input
using namespace std;
int main()
{
int num1, count = 0, num2[MAX];
char oper[MAX];
cin >> num1;
do{
cin >> oper[count] >> num2[count];
count = count + 1;
}while(oper[count -1 ] != '%');
int ans = num1, remainder = num2[count - 1]; // last number is remainder value
for(int i = 0; i < count - 1; i++)
{
if(oper[i] == '+')
ans = (ans % remainder + num2[i] % remainder) % remainder;
if(oper[i] == '*')
ans = (ans % remainder * num2[i] % remainder) % remainder;
}
cout << ans << endl;
}
关于c++ - 模块化计算器中的错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244736/