Jump to content

C error checking problem

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
s0n1c

s0n1c

    Newbie

  • Members
  • Pip
  • 6 posts
Hey guys;
I having a problem with a program that I'm creating. I need the program to get the users hourly rate for a job, and if they enter a negative number, or 0 it gives them an error message. So far this what what I have:
/* Enter hourly rate */

	printf("Enter hourly rate: ");

	scanf("%f", &hourlyRate);

	/* check hourlyRate */

	while(hourlyRate > 0)

	{	

		printf("*** ERROR: hourly rate must be positive\n");

		printf("Enter hourly rate: ");

		scanf("%f", &hourlyRate);	

	}//end while
I'm wanting the program to display this error message until a positive number higher than 0 is inputted. As is, the program runs an infinite loop.

Could someone please advice me what I am doing wrong.

Thanks in Advance;
S0n1C!

#2
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
    int hourlyRate = -1;
    
    printf("Enter hourly rate: ");
    scanf("%d", &hourlyRate);
    
    while(hourlyRate <= 0)
    {
        printf("\nHourly rate must be greater than 0!\n");
        
        printf("Enter hourly rate: ");
        scanf("%d", &hourlyRate);
    }
    
    printf("Your hourly rate is %d\n", hourlyRate);


#3
s0n1c

s0n1c

    Newbie

  • Members
  • Pip
  • 6 posts
Thanks, but this still causes an infinite loop. hourly rate is a double, because I need it to be a decimal. Is that the reason why it's not working?

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
You wrote your program to only accept non-positive values.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,720 posts
Your problem is that you wrote your program to input the number once. You need to read in the value inside the loop, otherwise it never asks for the input again, and keeps looping.


double hourlyRate = -1.0;


while(hourlyRate <= 0.0)

{

    printf("Enter hourly rate: ");

    scanf("%d",&hourlyRate);


    if(hourlyRate <= 0.0)

        printf("Invalid value. Hourly rate must be positive.\n");

}


//continue now that you have a valid value.



#6
s0n1c

s0n1c

    Newbie

  • Members
  • Pip
  • 6 posts
Hey guys;

I figured out my problem, here is the code that I used.
/* Enter hourly rate */

	printf("Enter hourly rate: ");

	scanf("%lf", &hourlyRate);

	/* check hourlyRate */

	while(hourlyRate <= 0)

	{	

			printf("*** ERROR: hourly rate must be positive\n");

			printf("Enter hourly rate: ");

			scanf("%lf", &hourlyRate);	

	}//end while

Since I am getting the user to input a floating point variable I added %lf, instead of just %f. Now the program works fine.

Thanks for the help;
S0n1C!