模块计算器中的错误答案

Wrong answer in modular calculator

本文关键字:错误 答案 计算器 模块      更新时间:2023-10-16

我创建了一个模块化计算器,用于执行一系列数学运算,并在最后对之前的所有内容进行修改。然而,我总是得到错误的结果。

#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

有什么解释吗?(BigIntdoubleunsigned int而不是int似乎无法解决任何问题;我已经尝试了所有这些)。

由于int溢出,您得到了错误的答案。

让我们给你一个例子

比如说你的输入低于

4
* 432
* 422
* 432
% 8

你的程序会给出错误的答案,因为

第一次输入后,ans=4*432=1728

第二次输入后,ans=1732*432=7746496(大于int的最高范围,发生int溢出并给出错误答案)

出于这个原因,我们可以使用下面的模算术公式,这样我们就可以留下int溢出。

  1. (A+B)%R=(A%R+B%R)%R
  2. (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;
 }