Home > OS >  How to make the rate be in any number. For example: rate = n
How to make the rate be in any number. For example: rate = n

Time:11-16

How can I fix this code? And also, my problem here is how to make the rate be in any number. For example: rate = n

#include<stdio.h>

int main(){

    int hours, rate, pay;

    hours = 40;
    rate = n;

    printf("Type forty: ");
    scanf("%d", &hours);

    printf("Your desired rate: ");
    scanf("%d", &rate);

    pay = 40 * rate;

    pay = hours*rate (hours-40)*rate*1.5;
    printf("The result is %d");

    return 0;
}

CodePudding user response:

The problem in your code is that you always calculate the overtime, even when the number of hours is less than 40; and in doing so, you calculate too much for the overtime.

So, instead of this:

pay = 40 * rate;

pay = hours*rate (hours-40)*rate*1.5;

where the first line has no effect anyway, as it is overwritten by the second line, write (for example)

if (hours <= 40) {
    pay = hours * rate;
}
else {
    pay = 40*rate (hours-40)*rate*1.5;
}

Please note that the literal 40 apperaring three times in the code is something that is ugly and should be replaced by a variable of symbolic constant.

CodePudding user response:

A more stable version of this code would be:

#include<stdio.h>

int main(void){

    unsigned int rate, hours;
    const unsigned int maxHours = 40;
    unsigned long pay = 0;

    printf("Type forty (or more): ");
    scanf("%i", &hours);
    printf("Your desired rate: ");
    scanf("%i", &rate);
    if(hours > maxHours) {
        pay = (hours*rate) (hours-maxHours)*rate*1.5;   
    }
    else {
        pay = hours*rate;   
    }
    
    printf("The result is %lu", pay);
    return 0;
}

This code addresses the following issues:

  1. It only calculates the additional pay if the hours exceed 40. The issue correctly identified by other answer here, credit to him!
  2. It takes care of the bug with missing argument in the last printf() where the pay value is intended to be printed
  3. [optional] Hours and rate is logically (most likely to be) always positive values, so uses unsigned int instead of int
  4. [optional] It covers the scenario if the rate value and hours value are high enough to overflow the range of unsigned int
  •  Tags:  
  • c
  • Related