模块计算器中的错误答案
Wrong answer in modular calculator
我创建了一个模块化计算器,用于执行一系列数学运算,并在最后对之前的所有内容进行修改。然而,我总是得到错误的结果。
#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=7746496(大于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;
}
相关文章:
- 递归求和任务的错误答案
- 为什么我在代码厨师的 CMPRSS 问题中得到 WA(错误答案)?
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 寻找最小楼梯成本的动态规划问题的错误答案
- 为什么可变大小的数组会导致Codechef出现错误答案
- 如何修复此代码对几个测试用例的错误答案?
- 使用幂函数的计算给出了大数字的错误答案
- 快速排序算法,一些特定输入序列的错误答案和分段错误
- 二分法程序的错误答案(C++)
- 无法理解绘图程序中的错误答案
- C++ - 整数除以整数返回错误答案
- 布尔函数的错误答案
- SPOJ FASTFLOW上的错误答案
- 代码的错误答案是在Java Camel案件和C 下划线标识符之间转换的错误答案
- 200万以下所有素数的总和,线程给出错误答案
- 0-1整数背包返回错误答案(动态编程)
- UVa 在线判断 - 3n + 1 - 错误答案
- 提升C++原始算法错误答案
- 二项式系数函数C++错误答案 n>13
- 需要帮助以避免 SPOJ 上的"错误答案"