简体   繁体   中英

C++ bug uninitialized variable

I am instructed to write a program where the user inputs two values, can be with decimals. Then create a void function that changes the precision to 4 digits. I created a program and it runs the first value (x) just fine but for some reason, it's giving me an error saying the second variable is uninitialized (h) any advice would be appreciated! I think that I've been looking at it for too long and just can't spot it!

Below is the code:

#include <iostream>
#include<cmath>

using namespace std;

void display_it(double x, double h);

int main(void) // getting input from user and displaying output
{
    double x, h;
    cout << "Please enter 2 values to be displayed with precision.\n";
    cin >> x, h;
    cout << x << endl;
   cout << h << endl;
   return 0;
}

void display_it(double x,double h) //does the precision change of x and h
{
   cout.setf(ios::fixed);
   cout.setf(ios::showpoint);
   cout.precision(4);
}

This line:

cin >> x, h;

is not reading in 2 values from cin . It's actually only reading in 1 value, after which the expression h that's after the , is evaluated (which does nothing). So the warning/error about h being uninitialized is correct.

The correct way to read 2 values is:

cin >> x >> h;

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