数学结果为零。编码新手

时间:2017-11-10 02:34:51

标签: c++

我试图完成一项作业,但我一般都对数学表达式和变量有困难。我试图创建一个程序,用于获取杂货的用户信息,然后输出收据。这是我的代码。

#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表示全部或负数。

2 个答案:

答案 0 :(得分:2)

您的计算必须在您阅读之前阅读,而不是之前。您根据未初始化的变量进行计算。

答案 1 :(得分:2)

声明和初始化,如

double firstExt = firstPrice * firstCount;

firstExt初始化为firstPricefirstCount的当前值的乘积。

它不会设置一些魔法,因此只要firstExtfirstPrice的值发生变化,就会重新计算firstCount的值。

在您执行此操作时,firstPricefirstCount是未初始化的变量。访问类型为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都会给编译器提供诊断。