我被要求编写一个程序,其中用户输入两个值,可以带小数。然后创建一个void函数,将精度更改为4位数字。我创建了一个程序,它很好地运行了第一个值(x),但是由于某种原因,它给我一个错误,指出第二个变量未初始化(h),任何建议都将不胜感激!我认为我已经看了太久了,只是找不到它!
下面是代码:
#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);
}
答案 0 :(得分:3)
此行:
cin >> x, h;
不是 从cin
中读取2个值。实际上,它仅读取1个值,然后对h
之后的表达式,
进行求值(不执行任何操作)。因此,关于h
尚未初始化的警告/错误是正确的。
读取2个值的正确方法是:
cin >> x >> h;