gpt4 book ai didi

c++ - 如何在 C++ 中初始化多个局部变量

转载 作者:太空宇宙 更新时间:2023-11-04 16:07:19 26 4
gpt4 key购买 nike

#include <iostream>
#include <iomanip>
using namespace std;

//Declares the prototype of function half().
float half1(float num1, float halfvalue1);
float half2(float num2, float halfvalue2);
float half3(float num3, float halfvalue3);

int main()
{
//Declares variables
float num1, num2, num3, halfvalue1, halfvalue2, halfvalue3;
//asks for values
cout << "Enter 3 real numbers and I will display their halves: " << endl << endl;
//stores values
cin >> num1, num2, num3;
//return half and assign result to halfvalue
halfvalue1 = half1(num1, 2.0);
halfvalue2 = half2(num2, 2.0);
halfvalue3 = half3(num3, 2.0);
//set precision
cout << fixed << showpoint << setprecision (3);
//Prints message with results
cout << halfvalue1 << halfvalue2 << halfvalue3 << " are the halves of " << num1 << num2 << num3 << endl;

return 0;
}

//function definition half
float half1(float num1, float halfvalue1)
{
return num1 / halfvalue1;
}

float half2(float num2, float halfvalue2)
{
return num2 / halfvalue2;
}

float half3(float num3, float halfvalue3)
{
return num3 / halfvalue3;
}

警告是:

warning C4700: uninitialized local variable 'num2' used warning C4700: uninitialized local variable 'num3' used

当我只使用一个变量时,我取得了圆满成功,但现在我不确定如何解决这个问题。

最佳答案

cin >> num1,num2,num3; 行的计算结果为三个独立的表达式:

  1. cin >> num1
  2. num2(被丢弃,因为没有副作用)
  3. num3(同样被丢弃)

逗号被视为运算符,而不是初始化列表。

试试这个:

cin >> num1;
cin >> num2;
cin >> num3;

或者这个:

cin >> num1 >> num2 >> num3;

关于c++ - 如何在 C++ 中初始化多个局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33272543/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com