减去 n 乘以整数值

subtract n times int value

本文关键字:整数 减去      更新时间:2023-10-16

我的代码减去n次数量:

int op = 0,quan,numbers,many;
cout << "Quantity to substract: " << endl;
        cin >> quan;
        cout << "Times to subs quantity:" << endl;
        cin >> many;
        for(int count = 1; count <= many; count++)
        {
            cout << "Insert " << count << " Number" << endl;
            cin >> numbers;                 
            op = quan - numbers;
        }
cout << "Total: " << op << endl;

但是不起作用。

程序运行:

Quantity to substract:
10
Times to subs quantity:
5
Insert 1 Number:
1
Insert 2 Number:
1
Insert 3 Number:
1
Insert 4 Number:
1
Insert 5 Number:
1
Total:
9

总计应5

你能支持我解决这个问题吗?谢谢

看起来这里的目标是从quan中减去所有 5 个数字。有问题的代码只减去最后一个。

要减去所有数字,请将结果变量初始化为第一个数字:

op = quan;

在循环中,从结果变量中减去:

op = op - numbers; // alternatively: op -= numbers

这是因为您在不使用以前的值 op 的情况下从quan中减去。在代码中,每次你做 : op = quan - numbers你失去了之前获得的状态。

int op = 0,quan,numbers,many;
cout << "Quantity to substract: " << endl;
        cin >> quan;
        cout << "Times to subs quantity:" << endl;
        cin >> many;
        // make op take the value of quan
        op = quan;
        for(int count = 1; count <= many; count++)
        {
            cout << "Insert " << count << " Number" << endl;
            cin >> numbers;        
            // substract from op           
            op = op - numbers;
        }
cout << "Total: " << op << endl;

试试这个:

int op = 0,quan,numbers,many;
cout << "Quantity to substract: " << endl;
        cin >> quan;
        cout << "Times to subs quantity:" << endl;
        cin >> many;
        for(int count = 1; count <= many; count++)
        {
            cout << "Insert " << count << " Number" << endl;
            cin >> numbers;                 
            op = quan - numbers;
            quan = op; // Add this so that new value is assigned to quan
        }
cout << "Total: " << op << endl;