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

最后发布: 2015-10-22 02:43:13


问题
#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'警告C4700:使用未初始化的局部变量'num3'

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

c++ variables
回答

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;
}

现场演示