Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read floating-point numbers by pairs in C?

Write a program that requests two floating-point numbers and prints the value of their difference divided by their product. Have the program loop through pairs of input values until the user enters nonnumeric input. Use a function to return the value of the calculation.

I've successfully completed this exercise without using function but can't get it right using function. The program itself runs but doesn't return any value in fact it crashes.

Please any help would be appreciated.

Here is my program:

#include <stdio.h>
#include <string.h>

double result (double x, double y);

int main(void)
{
     double num1, num2, res;
     printf("This while calculate difference of two numbers by their product.\n");
     printf("Enter first number followed by second number\n");

     while (scanf("%lf %lf", &num1, &num2 ==2))
     {
         res= result(num1, num2);
         printf("the result is equal to %.3g\n", res);
         printf("Enter next set of numbers or q to quit\n");
     }
     return 0;
}
double result(double x, double y)
{
    double output;
    output = (y-x)/(x*y);
    return output;
}
like image 240
Loofar Avatar asked Dec 25 '22 19:12

Loofar


2 Answers

while (scanf("%lf %lf", &num1, &num2 ==2))

was meant to be:

while (scanf("%lf %lf", &num1, &num2) ==2)
like image 166
LihO Avatar answered Dec 31 '22 13:12

LihO


Try changing

  while (scanf("%lf %lf", &num1, &num2 ==2))

to

 while (scanf("%lf %lf", &num1, &num2) ==2)
like image 21
Ed Heal Avatar answered Dec 31 '22 14:12

Ed Heal