同一个程序 returns 每次输出不同?

Same program returns different outputs each time?

每次我 运行 程序,使用完全相同的值(直径 25,深度 5),我得到 water_price 的不同值,我不确定为什么。

部分成果:

.62256e+07 is the total cost.
[=11=] is the total cost.
.43411e-27 is the total cost.

我不知道我是否在处理内存中的值,它们不能很好地相互配合,不能刷新或什么。

为什么我每次运行这个程序的结果都不一样?

#include <iostream>

#define PI 3.1416
#define WATER_COST 1.80

using std::cout;
using std::cin;
using std::endl;

int main() {

    float pool_diameter, pool_depth;
    float pool_radius = pool_diameter / 2;
    float pool_volume_sq_inches = (PI * pool_radius * pool_radius * pool_depth) * 1728;
    float pool_gallons = pool_volume_sq_inches / 231;
    float water_price = (pool_gallons / 748) * WATER_COST;

    cout << "Enter the pool diameter: ";
    cin >> pool_diameter;
    cout << "\nEnter the pool depth: ";
    cin >> pool_depth;

    cout << "\n$" << water_price << " is the total cost." << endl;

    return 0;
}

了解我们如何开始声明变量,然后当您要求输入时,它将存储在这些变量中,然后您可以继续进行所需的计算。

#include <iostream>
#define PI 3.1416
#define WATER_COST 1.80

using std::cout;
using std::cin;
using std::endl;

int main() {

    float pool_diameter = 0.0;
    float pool_depth = 0.0;

    cout << "Enter the pool diameter: ";
    cin >> pool_diameter;
    cout << "\nEnter the pool depth: ";
    cin >> pool_depth;


    float pool_radius = pool_diameter / 2;
    float pool_volume_sq_inches = (PI * pool_radius * pool_radius * pool_depth) * 1728;
    float pool_gallons = pool_volume_sq_inches / 231;
    float water_price = (pool_gallons / 748) * WATER_COST;


    cout << "\n$" << water_price << " is the total cost." << endl;

    return 0;
}

您可能希望在声明后尽快获得输入。

        float pool_diameter, pool_depth;

        cout << "Enter the pool diameter: ";
        cin >> pool_diameter;
        cout << "\nEnter the pool depth: ";
        cin >> pool_depth;

其余代码将按原样工作。

一个好的做法是像 Omid-CompSci 在这里回答的那样初始化你的变量。

语句float pool_radius = pool_diameter / 2;之前执行 cin >> pool_diameter;。每次都使用默认值(垃圾值)来计算pool_radius,这是不同运行中不同值的原因。

更改顺序。