数学结果为零.编码新手

Math results in zero. New to coding

本文关键字:编码 新手 结果      更新时间:2023-10-16

我正在尝试完成作业,但总的来说,我在数学表达式和变量方面遇到了困难。我正在尝试制作一个程序,该程序获取有关杂货的用户信息,然后输出收据。这是我的代码。

#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初始化为firstPricefirstCount点的当前值的乘积。

它没有设置一些魔法,因此每当更改firstPricefirstCount的值时,都会重新计算firstExt的值。

在您的情况下,执行此操作时,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 都会给编译器提供诊断。