C++ 变量在未初始化的情况下被使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12541061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Variable being used without being initialized
提问by David
So the variable hoursWorkedis not initialized. But how am I supposed to initialize it if I want it to equal whatever the user stores in it? For example I want hoursWorkedto be whatever any person outputs in it in cin. Here is my code:
所以变量hoursWorked没有被初始化。但是,如果我希望它等于用户存储在其中的任何内容,我应该如何初始化它?例如,我想hoursWorked成为任何人在cin. 这是我的代码:
#include <iostream>
using namespace std;
int main ()
{
//Declare Variables
double hoursWorked;
double payRate;
double incomeBeforeTax;
payRate = 15;
incomeBeforeTax = payRate * hoursWorked;
cout << "Enter hours worked: ";
cin >> hoursWorked;
cout << endl;
cout << incomeBeforeTax << endl;
return 0;
}
采纳答案by epsalon
The calculation of incomeBeforeTaxwhich references hoursWorkedneeds to occur after you initialize it by reading from cin. Move that line after cin >> hoursWorked;and it will work:
计算incomeBeforeTax其引用hoursWorked需要你通过阅读初始化后发生cin。移动该行之后cin >> hoursWorked;,它将起作用:
payRate = 15.0;
cout << "Enter hours worked: ";
cin >> hoursWorked;
incomeBeforeTax = payRate * hoursWorked;
cout << endl;
cout << incomeBeforeTax << endl;
C++, like most procedural languages evaluates your code in the order in which it is written. That is, incomeBeforeTax = payRate * hoursWorked;assigns a value to incomeBeforeTaxbased on the current values of payRateand hoursWorked. These must be defined and initialized before the assignment is performed. That is what cin >> hoursWorkeddoes.
C++ 与大多数过程语言一样,按照代码编写的顺序评估您的代码。也就是说,incomeBeforeTax = payRate * hoursWorked;分配一个值,以incomeBeforeTax基于所述电流值payRate和hoursWorked。这些必须在执行分配之前定义和初始化。这就是cin >> hoursWorked它的作用。
On a side note, doublevariables are best initialized with doubleliterals so add .0to the value.
附带说明一下,double变量最好用double文字初始化,因此添加.0到值中。
回答by R Sahu
By using
通过使用
incomeBeforeTax = payRate * hoursWorked;
before hoursWorkedhas been initialized, you seem to indicate the intent of what incomeBeforeTaxneeds to be. One way to preserve that intent is to create a function and use the function whenever you need incomeBeforeTax.
在hoursWorked被初始化之前,你似乎表明了incomeBeforeTax需要什么的意图。保留该意图的一种方法是创建一个函数并在需要时使用该函数incomeBeforeTax。
Example:
例子:
#include <iostream>
using namespace std;
int main ()
{
//Declare Variables
double hoursWorked;
double payRate;
// Define a function that encodes the intent of what
// incomeBeforeTax needs to be.
auto incomeBeforeTax = [&]() { return payRate*hoursWorked; };
payRate = 15;
cout << "Enter hours worked: ";
cin >> hoursWorked;
cout << endl;
cout << incomeBeforeTax() << endl;
return 0;
}

