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 hoursWorked
is 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 hoursWorked
to 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 incomeBeforeTax
which references hoursWorked
needs 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 incomeBeforeTax
based on the current values of payRate
and hoursWorked
. These must be defined and initialized before the assignment is performed. That is what cin >> hoursWorked
does.
C++ 与大多数过程语言一样,按照代码编写的顺序评估您的代码。也就是说,incomeBeforeTax = payRate * hoursWorked;
分配一个值,以incomeBeforeTax
基于所述电流值payRate
和hoursWorked
。这些必须在执行分配之前定义和初始化。这就是cin >> hoursWorked
它的作用。
On a side note, double
variables are best initialized with double
literals so add .0
to the value.
附带说明一下,double
变量最好用double
文字初始化,因此添加.0
到值中。
回答by R Sahu
By using
通过使用
incomeBeforeTax = payRate * hoursWorked;
before hoursWorked
has been initialized, you seem to indicate the intent of what incomeBeforeTax
needs 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;
}