如何在c++中初始化许多局部变量

How to initialize many local variables in C++

本文关键字:初始化 许多 局部变量 c++      更新时间:2023-10-16
#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;
}

警告如下:

警告C4700:未初始化的局部变量"num2"被使用使用未初始化的局部变量num3

我有充分的成功,当我只是使用一个变量,但现在我不确定如何解决这个问题。

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

  1. cin >> num1
  2. num2(因无副作用而丢弃)
  3. num3(也丢弃)

逗号作为操作符,而不是初始化列表。

试试这个:

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

或:

cin >> num1 >> num2 >> num3;

如上所述,错误是在cin >> num1, num2, num3;中使用逗号操作符。

使用数组可以清理代码:

#include <algorithm>
#include <iostream>
#include <iomanip>
float half(float num)
{
    return num / 2;
}
int main()
{
    // Declares variables
    float nums[3]; // or std::array<float, 3> nums; or std::vector<float> nums(3);
    float halfvalues[3];
    //asks for values
    std::cout << "Enter 3 real numbers and I will display their halves: " << std::endl
              << std::endl;
    //stores values
    for (auto& v : nums) {
        std::cin >> v;
    }
    //return half and assign result to halfvalue
    std::transform(std::begin(nums), std::end(nums), std::begin(halfvalues), &half);
    //set precision
    std::cout << std::fixed << std::showpoint << std::setprecision (3);
    //Prints message with results
    for (const auto& v : halfvalues) {
        std::cout << " " << v;
    }
    std::cout << " are the halves of ";
    for (const auto& v : nums) {
        std::cout << " " << v;
    }
    std::cout << std::endl;
}

现场演示