1

所以变量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;
}
4

2 回答 2

1

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:

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.

On a side note, double variables are best initialized with double literals so add .0 to the value.

于 2012-09-22T05:45:30.907 回答
0

通过使用

incomeBeforeTax = payRate * hoursWorked;

hoursWorked被初始化之前,你似乎表明了incomeBeforeTax需要的意图。保持这种意图的一种方法是创建一个函数并在需要时使用该函数incomeBeforeTax

例子:

#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;
}
于 2017-09-21T19:38:30.933 回答