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

标签 c++ variables

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

相关文章:

c++ - 如何编写 KSP 以连接到 KERB_CERTIFICATE_LOGON

javascript - Fullcalendar:如何从两个变量获取事件并通过 'eventAfterRender' 传递?

c++ - 使用 CPack 时防止为已安装的共享库创建名称链接

c++ - 外部如何工作?

python - 尝试在 Visual Studio 2013-15 中从 C++ 执行 python 脚本时出现导入错误

variables - 如何让 Tomcat 的logging.properties 识别我的 Catalina 变量?

javascript - 使用变量更改 CSS 和 JS

c# - 在 C# 中,为什么我在声明它时看到我的 int 变量中存储了一个零,但仍然收到一条错误消息说我应该初始化它?

java - 如何从另一个 Activity 访问数据?

c++ - 使用用户输入的数据创建结构数组