I need to write a program that requests two floating-point numbers and prints the value of
their difference divided by their product, and to have the program loop through pairs of
input values until the user enters nonnumeric input. I need to use scanf to take the input.
So, as I know that scanf return a value 0 or 1 for true/false so I though testing it to accomplish the last part of the question, but I’m trying to figure out how to make sure the loop goes back to ask for input.
My code is:
int main()
{
double num1, num2, different, product, answer;
printf("please enter 2 floatig point numbers:\n");
printf("number one is?\n");
while (scanf("%lf", &num1) ==1)
{
printf("number two is?\n");
while (scanf("%lf", &num2) ==1)
{
if (num1 > num2)
{
different = num1 - num2;
}
if (num2 > num1)
{
different = num2 - num1;
}
if (num1 == num2)
{
different = 0;
}
product = num1*num2;
answer = different/product;
printf("%lf", answer);
}
printf("you're out!");
}
printf("you're out!");
}
Example input:
first num 4.5
second num 3.5
output:
please enter 2 floatig point numbers:
number one is?
4.5
number two is?
3.5
0.063492
I’m getting the right answer and the program keeps running but I’m looking for a solution to go back for the input request.
You should first note that whatever made your
scanffail the first time, will probably make it fail the second time. So a loop such as this:could become an infinite loop.
Also, when reading two or more values at the same time, it would be hard to track what is read and what is not. Therefore, I advise reading the values one by one, in a form like this:
What this basically does is try reading the value until the user produces a correct one. In case of incorrect input, one line of input is consumed and thrown away so the left over of whatever the user has input would not affect the next
scanfand create a chain of errors.