减去 n 乘以整数值
subtract n times int value
我的代码减去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;
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 当我们从/tp地址中添加/减去一个整数时会发生什么
- C++字符串大小减去整数不是预期值,为什么?
- 减去CPP整数时,我会丢失一个数字
- 整数减去一个类
- 从整数中减去指针
- 如何从另一个整数中减去两个整数的总和,然后将其递增
- **签名的**正整数会导致溢出的一单位减去操作员
- 减去迭代器和整数
- INT_MIN从被视为未定义行为的任何整数中减去
- 如果使用无符号整数,则通过减去1将基于1的编号转换为基于0的编号是否安全
- 减去无符号整数的有符号结果
- 减去一个数组c++中的两个长正整数
- 从无符号整数减去有符号整数