在c ++中调用函数时,我的程序崩溃了

时间:2013-10-21 15:36:07

标签: c++

所以我必须做三个功能。一个问一个公司有多少员工。另一个问他们错过了多少天。第三个通过将员工数除以缺失的天数来计算平均值。在主要方面,我所要做的就是有cout提示并调用函数。我不确定我是否做得对,但是当它必须计算平均值时会崩溃。

#include <iostream>
#include <iomanip>
using namespace std;

int employee(int employeeNum);
int missingDays(int daysMissing);
double getAvg(int employeeNum,int daysMissing,double average);

int employee(int employeeNum)
{
  cout<<"Enter the number of employee in the company.";
  cin>>employeeNum;
  return employeeNum;
}

int missingDays(int daysMissing)
{
  cout<<"Enter the amount of days employees missed during the past year.";
  cin>>daysMissing;
  return daysMissing;
}

double getAvg(int employeeNum,int daysMissing,double average)
{
  average=employeeNum/daysMissing;
  return average;
}

int main()
{
  int employeeNum,people,missing,daysMissing;
  double avg,average;

  people=employee(employeeNum);
  cout<<"The number of employees in the company is "<<people<<"."<<endl;

  missing=missingDays(daysMissing);
  cout<<"The number of days employees missed during the past year is "<<missing<<".";

  avg=getAvg(employeeNum,daysMissing,average);
  cout<<average;
}

让我知道我要做什么,并感谢你的帮助。

4 个答案:

答案 0 :(得分:2)

这看起来像是家庭作业,所以你应该只期待轻推。所以,一些推动:为什么你的函数employee()missingDays()会得到参数?为什么getAvg()需要3?您的输入值最终会在哪些变量中出现?它们在哪里使用(如果有的话)?

答案 1 :(得分:1)

你的问题就在这一行

missing=missingDays(daysMissing);

由于某种原因,你有两个“daysMissing”变量(我不知道为什么你首先将它传递给你的missingDays函数)

在该行之后,missing将包含值输入,而不是daysMissing(因为它未通过引用传递)

你的getAvg函数可能会因为零错误而崩溃。

答案 2 :(得分:0)

因此,根据编译器,daysMissing的值未定义或使用0进行初始化。

在您的函数getAvg中划分employeeNum/daysMissing;

但是你不能被零除,这就是它:)

答案 3 :(得分:0)

#include <iostream>
#include <iomanip>
using namespace std;

int employee(int employeeNum);
int missingDays(int daysMissing);
double getAvg(int employeeNum,int daysMissing,double average);

int employee(int employeeNum)
{
  cout<<"Enter the number of employee in the company: ";
  cin>>employeeNum;
  return employeeNum;
}

int missingDays(int daysMissing)
{
  cout<<"Enter the amount of days employees missed during the past year: ";
  cin>>daysMissing;
  return daysMissing;
}

double getAvg(int employeeNum,int daysMissing)
{
    if(daysMissing == 0)
    {
        return 0;
    }
  return (double)employeeNum/daysMissing;;
}

int main()
{
  int employeeNum,people,missing,daysMissing;
  double avg,average;

  people=employee(employeeNum);
  cout<<"The number of employees in the company is: "<<people<<"\n";

  missing=missingDays(daysMissing);
  cout<<"The number of days employees missed during the past year is: "<<missing<<"\n";

  avg=getAvg(people,missing);
  cout<<avg;
}