c++ - 同一程序每次返回不同的输出?

标签 c++ initialization non-deterministic

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

一些结果:

$6.62256e+07 is the total cost.
$0 is the total cost.
$2.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;
}

关于c++ - 同一程序每次返回不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58704714/

相关文章:

c++ - operator new 在内存不足时不返回 0

C++ 初始化类成员构造函数

c# - 在集合/对象初始值设定项中使用 Random.Next()

Python浮点确定性

haskell - 非确定性合并排序不按字典顺序排列排列

numpy - 浮点非确定性的原因?包括 NumPy?

c++ - 如何使用 shared_ptr 从外部提供模拟对象?

c++ - 为什么 C 和 C++ 编译器在从未强制执行时允许函数签名中的数组长度?

c++ - 获取纳秒级的时间差

c - 指针初始化字符串文字