谁能告诉我为什么这个结果一直为0? (C程序)

时间:2018-08-10 09:41:10

标签: c

    case 2:
        if(hrswrk <= 40)
            pay = wage * hrswrk;
        else
            pay = (40 * wage) + (hrswrk - 40) * (wage * 1.5);
        printf("Hourly Workers is selected. \n");
        printf("Enter number of hours worked: \n");
        scanf("%i",&hrswrk);
        printf("Enter hourly wage: \n");
        scanf("%i",&wage);
        printf("Your pay is Php%.2f",pay);
        break;

这只是我程序的一部分,令人沮丧的是我什至无法解决它,也许错误是我在开关中放置了if else语句?我很迷路。

4 个答案:

答案 0 :(得分:2)

在获取所需数据后进行操作:

case 2:
    printf("Hourly Workers is selected. \n");
    printf("Enter number of hours worked: \n");
    scanf("%i",&hrswrk);
    printf("Enter hourly wage: \n");
    scanf("%i",&wage);

    if(hrswrk <= 40)
        pay = wage * hrswrk;
    else
        pay = (40 * wage) + (hrswrk - 40) * (wage * 1.5);

    printf("Your pay is Php%.2f",pay);
    break;

答案 1 :(得分:1)

在建立payhrswrk的值之后,需要计算wage ,即,移动if在最后一次scanf通话之后

尽管某些语言以您编写的方式工作,但C却没有。

还请注意,您应始终检查scanf的返回值,以检查读取是否成功。

答案 2 :(得分:0)

if-condition之后执行scanf()

在您的代码中,您正在执行if-condition,然后再读取hrswrkwage。首先阅读它们并执行if-logic

尝试此修改后的代码:-

case 2:
    printf("Hourly Workers is selected. \n");
    printf("Enter number of hours worked: \n");
    scanf("%i", &hrswrk);
    printf("Enter hourly wage: \n");
    scanf("%i", &wage); 

    if (hrswrk <= 40)   // if condition after scanning wage and  hrswrk
        pay = wage * hrswrk;
    else
        pay = (40 * wage) + (hrswrk - 40) * (wage * 1.5);
    printf("Your pay is Php%.2f", pay);
    break;

这将起作用。

答案 3 :(得分:0)

 case 2:
        printf("Hourly Workers is selected. \n");
        printf("Enter number of hours worked: \n");
        scanf("%i",&hrswrk);
        printf("Enter hourly wage: \n");
        scanf("%i",&wage);
       if(hrswrk <= 40)
            pay = wage * hrswrk;
        else
            pay = (40 * wage) + (hrswrk - 40) * (wage * 1.5);
        printf("Your pay is Php%.2f",pay);
        break;