我无法弄清楚为什么我的程序在GDB Online中起作用,但在代码:块中不起作用。它应该允许一个人输入其小时率,然后输入他们在过去4周内工作了多少小时,将这些总数添加在一起,然后将总计退还给用户。它应该使用花费时间作为参数的函数。在代码中:阻止它在输入第一个小时数之后终止程序。这是代码:
#include <iostream>
#include <iomanip>
using namespace std;
// function declaration
float getGross(float hs[], int n);
int main()
{
float hours[4], sum;
sum = getGross(hours, 4);
cout << "Gross pay: $ " << setprecision(2) << fixed << sum << endl;
return 0;
}
// function definition
float getGross(float hs[], int n)
{
float wage, ot, total;
cout << "Please enter your hourly wage: " << endl;
cin >> wage;
cout << "Enter hours worked in each of the past four weeks (hit enter after each entry): " << endl;
// Storing 4 number entered by user in an array
for (int i = 0; i < n; ++i)
{
// Holding the array of hours entered
cin >> hs[i];
int j;
float weekPay[4];
if(hs[i] > 40)
{
ot = (hs[i] - 40) * 1.5;
weekPay[j] = (wage * 40) + (ot * wage);
total += weekPay[j];
}
else
{
weekPay[j] = (wage * hs[i]);
total += weekPay[j];
}
}
return total;
}
变量int j
,在第40行中并不活化,这会导致运行时错误。
试图清理代码:
// function definition
float getGross(float hs[], int n)
{
float wage, ot, total = 0;
cout << "Please enter your hourly wage: " << endl;
cin >> wage;
cout << "Enter hours worked in each of the past four weeks (hit enter after each entry): " << endl;
// Storing 4 number entered by user in an array
for (int i = 0; i < n; ++i)
{
// Holding the array of hours entered
cin >> hs[i];
if (hs[i] > 40)
{
ot = (hs[i] - 40) * 1.5;
total += (wage * 40) + (ot * wage);
}
else
{
total += (wage * hs[i]);
}
}
return total;
}