繁体   English   中英

同一个程序每次返回不同的输出?

[英]Same program returns different outputs each time?

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

一些结果:

$6.62256e+07 is the total cost.
$0 is the total cost.
$2.43411e-27 is the total cost.

我不知道我是否正在处理 memory 中的值不能很好地相互配合,不冲洗或什么。

为什么每次运行此程序时结果都不同?

#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;

Rest 代码将按原样工作。

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

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

更改顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM