减去 n 倍的 int 值
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
这是因为你从quan
中减去,而没有使用op
之前的值。
每次在你的代码中: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;
我的代码减去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
这是因为你从quan
中减去,而没有使用op
之前的值。
每次在你的代码中: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;