如何在c++中初始化许多局部变量
How to initialize many local variables in C++
#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;
行计算为三个独立的表达式:
-
cin >> num1
-
num2
(因无副作用而丢弃) -
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;
}
现场演示
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 在C和C++中初始化结构中的数组
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 如何在c++中初始化许多局部变量
- 在初始化列表中初始化许多对象成员变量