3

我正在做一个程序,该程序将输入该周的每周工资和总工作时间。它应该以小时工资率显示答案。但我无法显示正确的“centavos/2 个小数位”公式,并且它不想使用 float % float 运行。请帮忙!

#include <stdio.h>

int gethourpaypes(int weekpay, int hoursworked)
{
  int hourpaypes;
  hourpaypes = weekpay / hoursworked;
  return hourpaypes;
}

int gethourpaycent(int weekpay, int hoursworked)
{
  int hourpaycent;
  hourpaycent = ((weekpay / hoursworked) % 100);
  return hourpaycent;
}

int main()
{
  int hourpaypes, weekpay, hoursworked;
  int hourpaycent;
  printf("Enter total week pay in pesos: ");
  scanf("%d", &weekpay);
  printf("Enter total hours worked that week: ");
  scanf("%d", &hoursworked);
  hourpaypes = gethourpaypes(weekpay, hoursworked);
  hourpaycent = gethourpaycent(weekpay, hoursworked);
  printf("Your hourly pay rate is %.0d pesos and %.2d centavos", hourpaypes, hourpaycent);
  fflush(stdin);
  getchar();
}
4

3 回答 3

1

恐怕你的两个计算都不正确。比索计算实际上计算的是小时工资,你似乎只得到整数比索,因为你打印它时没有小数。

时薪是

hourpay = weekpay / hoursworked;

从中,您可以获得以比索为单位的小时工资,floor()以获得一个整数(不是int)数字:

pesos = floor(hourpay);

和centavos作为余数;这通常使用 来完成round(),因此 12.345 变为 12 比索和 35 分(但您可以使用floor()而不是截断它round()):

cvos  = round(100.0*(hourpay - pesos));

整数运算

您将周薪换算为分,然后除以工作时间。为了将舍入误差降至最低,您将所有内容保留float到最后一刻。

int main()
{
    float weekpay, hoursworked;
    int centavos_per_hour, psos, cvos;

    printf("Enter total week pay in pesos: ");
    scanf("%f", &weekpay);
    printf("Enter total hours worked that week: ");
    scanf("%f", &hoursworked);

    centavos_per_hour = (weekpay * 100.0) / hoursworked;

    psos = centavos_per_hour / 100;  // Hourly pay is 2345 co = 23 pesos
    cvos = centavos_per_hour % 100;  // 

    printf("Your hourly pay is %d pesos %d centavos per hour\n", psos, cvos);

    return 0;
}
于 2012-10-08T10:07:21.973 回答
1

用于fmod计算浮点余数。%运算符只能与整数类型的操作数一起使用。

#include <math.h>
double fmod(double x, double y);
float fmodf(float x, float y);
于 2012-10-08T10:01:06.997 回答
1

不要给自己和他人制造麻烦,不要用float/double/etc来代表金钱。使用整数,其中 1 是最小的货币单位,在您的情况下是 cent(avo)。

于 2012-10-08T10:12:02.580 回答