#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'使用
当我只使用一个变量时,我取得了圆满成功,但现在我不确定如何解决这个问题。
答案 0 :(得分:5)
第cin >> num1,num2,num3;
行评估为三个单独的表达式:
cin >> num1
num2
(因为没有副作用而被丢弃)num3
(也被丢弃)逗号被视为运算符,而不是初始化列表。
请改为尝试:
cin >> num1;
cin >> num2;
cin >> num3;
或者这个:
cin >> num1 >> num2 >> num3;
答案 1 :(得分:0)
如上所述,错误在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;
}