我正在努力学习如何使用C编程 现在我一直在尝试编写薪水检查程序
对你们来说会很容易。我是一个初学者
我不知道如何调用函数
你们能帮我吗?
非常感谢
#include <stdio.h>
#include <stdlib.h>
float calculatePay(float payRate, float hours);
float hours = 50;
float payRate = 10;
float regHours;
float overtimeHours;
float regPay;
float overtimePay;
float grossPay;
float overtimeRate1 = 0.5;
int main()
{
printf("The pay check for the first person is: %0.2f\n", calculatePay(payRate, hours), grossPay+overtimePay);
}
float calculatePay(float payRate, float hours)
{
regPay = regHours * payRate;
overtimePay = overtimeHours * payRate * overtimeRate1;
grossPay = regPay + overtimePay;
if (hours <= 40){
regHours = hours;
overtimeHours = 0;
return grossPay+overtimePay;
}
else if (hours > 40);{
regHours = 40;
overtimeHours = regHours - 40;
return grossPay+overtimePay;
}
}
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
float calculatePay(); // Changed function prototype
// Global floats are default initialized to 0
float hours = 50;
float payRate = 10;
float regHours;
float overtimeHours;
float regPay;
float overtimePay;
float grossPay;
float overtimeRate1 = 0.5;
int main() {
printf("Enter gross pay, over time pay and overtime hours:\n");
if (scanf("%f %f %f", &grossPay, &overtimePay, &overtimeHours)<3) {
perror("input failure for gross pay, over time pay and overtime");
exit(EXIT_FAILURE);
}
printf("The pay check for the first person is: %0.2f\n",
calculatePay()); // No need to pass arguments, since they are global
// variables
}
float calculatePay() {
regPay = regHours * payRate;
overtimePay = overtimeHours * payRate * overtimeRate1;
grossPay = regPay + overtimePay;
if (hours <= 40) {
regHours = hours;
overtimeHours = 0;
return grossPay + overtimePay;
}
// else { No need of else condition since you are returning in if
regHours = 40;
overtimeHours = regHours - 40;
return grossPay + overtimePay;
//}
}
说明(对于新手;请阅读链接的文档):
calculatePay
函数。main
是default function,它是在您运行C程序时执行的。stdout
已被缓冲(通常是行缓冲),因此您通常希望以\n
结束其格式控制字符串(或适当地调用fflush)。%d
,%f
等被称为格式说明符,它们在printf
或scanf
的字符串中使用,它们表示变量的数据类型,例如int,float,等等。void foo(int, int);
函数之后定义了函数(也称为函数声明),则必须编写函数的原型(如main
)。阅读How to debug small programs。不要忘记在编译时启用所有警告和调试信息(并改进您的代码以获取任何警告)。如果使用GCC,请编译with gcc -Wall -Wextra -Wno-prototypes -g
。