C ++代码在GDB在线工作,但不在代码:块

时间:2018-02-19 13:43:30

标签: c++ arrays function

我无法弄清楚为什么我的程序在GDB在线工作但在Code:Blocks中不起作用。它应该允许一个人输入他们的小时费率,然后输入他们在过去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;
}

1 个答案:

答案 0 :(得分:1)

第40行的变量int j未初始化并导致运行时错误。

试图清理代码:

// 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;
  }