数学结果为零.编码新手
Math results in zero. New to coding
我正在尝试完成作业,但总的来说,我在数学表达式和变量方面遇到了困难。我正在尝试制作一个程序,该程序获取有关杂货的用户信息,然后输出收据。这是我的代码。
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
程序输出 0 表示全部或负数。
您的计算必须在您读取值之后进行,而不是在读取之前。您正在根据未初始化的变量进行计算。
声明
和初始化,如
double firstExt = firstPrice * firstCount;
将firstExt
初始化为firstPrice
和firstCount
点的当前值的乘积。
它没有设置一些魔法,因此每当更改firstPrice
或firstCount
的值时,都会重新计算firstExt
的值。
在您的情况下,执行此操作时,firstPrice
和 firstCount
是未初始化的变量。 访问类型 int
的未初始化变量的值会产生未定义的行为。
你需要做的是这样的
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
如果在此之前不需要 firstExt
的值,则可以在此处声明它;
double firstExt = firstPrice*firstCount; // do the calculation here
这意味着任何早期使用 firstExt
都会给编译器提供诊断。
相关文章:
- 如何确定我已使用非编码文件到达 EOF?
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 在卡萨布兰卡形成编码参数的列表
- 我是c ++的新手,你能解释一下在这种情况下的指针吗
- 使用C++进行游程编码
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 使用已使用 java 编码的 openssl 解码数据
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- 我是编程新手
- boost 是否有按特殊类型值编码状态"compact optional"?
- 如何在CPP的给定目录中列出UTF编码的文件名?
- 如何使用 C++将 ISO-2022-KR 编码转换为 UTF-8 编码?
- 绝对编码器十六进制输入
- 编码新手需要有关 if 语句的帮助
- 我是编码新手,我面临一个问题
- 数学结果为零.编码新手
- C++的新手,编码语法
- 新手编码器在这里: C++ 使用函数将向量复制到数组中
- 我想我试图在我的变量中传递错误的数据?里面的新手编码器