gpt4 book ai didi

c++ - 相加不是相乘

转载 作者:太空宇宙 更新时间:2023-11-04 15:19:54 27 4
gpt4 key购买 nike

我正在自学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 件

not adding

最佳答案

它不会对总价做任何事情,因为它总是0

int total = price * quantity;

乘法的结果在这个点执行并“保存”,即使pricequantity以后也不会改变做。

您应该将此行放在您真正设置 pricequantity 值的行之后

至于你关于“加法而不是乘法”的问题,修复如上 the value output is correct ,所以你肯定做错了我们看不到的事情。检查您是否正在运行代码,而不是其他代码。

此外,您一直在编写 /n,而它应该是 \n(这进一步表明您的屏幕截图不是来自运行 this代码)。实际上,输入提示之前的两个应该是 endl,以确保将提示刷新到控制台。

关于c++ - 相加不是相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22013708/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com