错误 1 错误 C4700:未初始化的局部变量'rate'并在C++中'hours'

Error 1 error C4700: uninitialized local variable 'rate' and 'hours' in C++

本文关键字:错误 rate 并在 hours C++ 局部变量 C4700 初始化      更新时间:2023-10-16

我是编程初学者。我正在编写一个C++程序,用户会显示他们的工资和工作时间,然后计算工资和工作小时数,然后显示它。我完成了程序,有两个错误我试图修复,但我仍然无法修复。错误和我的代码如下。有人能帮我,告诉我怎么修吗?我正在使用MSVS Express 2013。

错误:

Error   1   error C4700: uninitialized local variable 'hours'
Error   2   error C4700: uninitialized local variable 'rate'

(它在displayWeekly(rate, hours);上出错)

我的代码:

#include "stdafx.h"
#include<iostream>
using namespace std;
void displayWeekly(double rate, int hours);
double getRate();
int getHours();
int main()
{
double rate; 
int hours;
displayWeekly(rate, hours);
double getRate();
int getHours();
rate = getRate();
hours = getHours();
system("pause");
return 0;
}
void displayWeekly(double rate, int hours)
{
double weekPay;
weekPay = rate * hours;
cout << "Weekly pay is " << weekPay << endl;
}
double getRate()
{
double rate;
cout << "Enter your Hourly rate in the Dollars and Cents = ";
cin >> rate;
return rate;
}
int getHours()
{
int time;
cout << "Please Enter in the Hours you worked" << endl;
cout << "You must Enter a whole Number = ";
cin >> time;
return time;
}

您的新main应该是这样的:

int main()
{
    double rate;
    int hours;
    //double getRate(); --> where do you think the return value is stored to?
    //int getHours();   --> 
    rate = getRate();
    hours = getHours();
    displayWeekly(rate, hours);  // --> has to go after you put values to rate & hours
    system("pause");
    return 0;
}

将未初始化的变量传递给displayWeekly,将它们相乘并打印,这将导致错误。相反,在调用getHoursgetRate之后再调用该函数,以便对它们进行初始化。

还有

double getRate(); 
int getHours();

main中是不必要的。拆下它们。

这里您所犯的主要错误是忽略代码的顺序(流)。

int main()
{
double rate; 
int hours;
displayWeekly(rate, hours);//-> this is the func call that lead to error,cozz the arguments rate,hours are not still initialized .You calculated them after the function call.
double getRate();
int getHours();
rate = getRate();
hours = getHours();
                   //->it helps if you call display func here.
system("pause");
return 0;
}