如何在C中成对读取浮点数?

时间:2013-10-12 21:49:00

标签: c io floating-point double scanf

编写一个请求两个浮点数的程序,并打印它们的差值除以它们的乘积。让程序循环通过成对的输入值,直到用户输入非数字输入。 使用函数返回计算值。

我已成功完成此练习而不使用功能但无法使用功能正确完成此练习。程序本身运行但没有返回任何值,实际上它崩溃了。

请任何帮助将不胜感激。

这是我的计划:

#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;
}

2 个答案:

答案 0 :(得分:8)

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

原意是:

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

答案 1 :(得分:2)

尝试更改

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

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