简体   繁体   中英

Same program returns different outputs each time?

Every time I run the program, using the exact same values (25 for diameter and 5 for depth), I am getting different values for water_price and I'm not sure why.

Some of the outcomes:

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

I don't know if I am dealing with values in memory not playing well with each other, not flushing or what.

Why are the outcomes different every time I run this program?

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

See how we need to declare the variables to begin with, then when you ask for input it will be stored in those variables, and then you can continue on with the calculations you need.

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

You may want to get the inputs soon after the declaration.

        float pool_diameter, pool_depth;

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

Rest code would work the way it is.

A good practice would be to initialize your variables like Omid-CompSci has answered here.

Statement float pool_radius = pool_diameter / 2; is executed before cin >> pool_diameter; . Default value(garbage value) is used every time to calculate the pool_radius that is reason for different values in different runs.

change the order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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