繁体   English   中英

C - 从 function 返回浮点值并打印它们

[英]C - Returning Float values from a function and printing them

我不确定我在这里做错了什么,但这总是将最后的平均变量打印为 0。

我尝试了多种方法,这是我得到的最接近的平均值,没有错误或警告,我得到的警告是 68 总毛默认为 int,68 计数器默认为 int。

#include <stdio.h>

#include <stdlib.h>

float finalCalc();

int main(){

int yORn = 1;

float totalGross;
float counter = 0;
float commissionEarned;
float grossPay;
float overTime;
char employeeCode;

do{

counter++;


printf("Please enter employee code:\n");
scanf(" %c", &employeeCode);

float hoursWorked;
printf("Please enter the hours they worked:\n");
scanf("%f", &hoursWorked);

float hourlyWageRate;
printf("Please enter there hourly rate in œ:\n");
scanf("%f", &hourlyWageRate);

if(employeeCode == 's' || employeeCode == 'S'){
        printf("Please enter any commission they have earned in œ:\n");
        scanf("%f", &commissionEarned);}

if(employeeCode == 's' || employeeCode == 'S'){
        grossPay = (hoursWorked * hourlyWageRate) + commissionEarned;
        printf("Department: Sales\nEmployee Code: %c\nGross pay: œ%6.2f\n", employeeCode, grossPay);
}

else if(employeeCode == 'f' || employeeCode == 'F'){
        overTime = (hoursWorked - 35) * 1.5;
        grossPay = (hoursWorked + overTime) * hourlyWageRate;
        printf("Department: Factory\nEmployee Code: %c\nGross pay: œ%6.2f\n", employeeCode, 
grossPay);
}

else{
        grossPay = (hoursWorked * hourlyWageRate);
        printf("Department: Admin\nEmployee Code: %c\nGross pay: œ%6.2f\n", employeeCode, grossPay);
}

totalGross = totalGross + grossPay;
printf("Would you like to enter another employee? 1 for yes 2 for no\n");
scanf("%d", &yORn);

}while(yORn == 1);
float average = finalCalc(totalGross, counter);
printf("The total gross pay was: œ%6.2f\nThe average gross pay was: œ%0.2f", totalGross, average);

return 0;}

float finalCalc(totalGross, counter){
float averageGross = totalGross / counter;
return averageGross;
};

float finalCalc(totalGross, counter)将参数声明为 int。 在这种情况下,int/int 产生 0。声明为: float finalCalc(float totalGross, float counter)

开始时您还需要一个原型,否则编译器将假定参数为 int 并在调用 function 之前将您的浮点数转换为 int。

我建议打开编译器的警告。 大多数编译器会针对这些情况发出警告。

您的代码和使用编译器的方式有四个明显的问题:

  1. 在开发过程中编译 C 程序时,应始终启用警告。 不幸的是,默认情况下通常不会启用警告。 如果您使用 gcc 您只需将选项-Wall添加到命令中。

  2. 当您启用警告时,编译器会发出类似

    test.c: In function 'finalCalc': test.c:68:7: warning: type of 'totalGross' defaults to 'int' [-Wimplicit-int] float finalCalc(totalGross, counter) ^~~~~~~~~ test.c:68:7: warning: type of 'counter' defaults to 'int' [-Wimplicit-int]

    使用 integer 除法,您得到零而不是零和一之间的数字。

  3. 变量计数器不应该是 integer 而不是浮点数吗?

  4. 您需要检查scanf的返回值,以确保用户输入了正确类型的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM