我正在教自己C++,从基础开始写如下:
// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string mystr;
int price = 0;
int quantity = 0;
int total = price * quantity;
cout << "------------------------------------------------------" << '/n';
cout << "-----------------Welcome to the shop!-----------------" << '/n';
cout << "------------------------------------------------------" << '/n';
cout << "Enter price of item" << '/n';
getline(cin, mystr);
stringstream(mystr) >> price;
cout << "How Many do you want?" << '/n';
getline(cin, mystr);
stringstream(mystr) >> quantity;
cout << "you want this many: " << quantity << '/n';
cout << "at this price: " << price << '/n';
cout << "this would cost you: " << total << " pounds" << '/n';
if (total >= 20)
{
cout << "here is a discount of " << total / 20 << '/n';
}
else if (total >= 10)
{
cout << "here is a discount of " << total / 10 << '/n';
}
else
{
cout << "sorry no discount" << '/n';
};
}我唯一的问题是-它增加了总价格,而不是成倍增长。我觉得我错过了一些非常明显的东西,但一个小时后,我似乎找不出它是什么,我试着在代码中再声明一个不起作用的总数,我还试着将总数放在括号中,仍然什么也没有。
我遗漏了什么?
-举个例子-- 10个单元,每台10台,应该是100台,而不是我的代码上的20台。

发布于 2014-02-25 12:10:27
它不会用总价来做任何事情,因为它永远是0。
int total = price * quantity;乘法的结果在此时被执行并“保存”,即使price和quantity这样做,以后也不会改变。
您应该将这一行放在真正设置price和quantity值的行之后。
至于您关于“添加而不是乘积”的问题,与上面的值输出是正确的。修复相同,所以您肯定做了一些我们看不到的错误。检查您是否正在运行此代码,而不是运行其他代码。
而且,您一直在编写/n,而应该是\n (这进一步表明您的屏幕快照不是运行此代码的结果)。实际上,输入提示符之前的两个应该是endl,以确保提示被刷新到控制台。
发布于 2014-02-25 12:10:13
你在错误的地方计算总数。最初,使用price = 0和quantity = 0计算0,这将将0分配给total。然后,在输入quantity和price之后,您不会重新计算total,因此它会给出错误的结果。
我的建议是把total = price * quantity;放在stringstream(mystr) >> quantity;之后
发布于 2014-02-25 12:12:52
auto total = [&]() { return price * quantity; };然后使用total()
http://coliru.stacked-crooked.com/a/27ba0fa6978ec9e1
https://stackoverflow.com/questions/22013708
复制相似问题