请在第7章编程之后看看我作为作业的一部分编写的程序。程序应该根据用户输入的常量值返回二次曲线的根。该计划应该非常简单;我处于初级水平。 虽然编译器确实编译了程序,但我得到的唯一输出是提示消息。但在我输入三个值后,没有任何反应,程序结束,我回到了终端。 我编辑了这个程序。现在,如果我输入一些使判别式小于0的值,我得到
Please, enter three constants of the quadratic:
1 2 3
Roots are imaginary
Square roots of this quadratic are:
因此主要功能声明仍然出现。
如果我输入其他值,我会
Please, enter three constants of the quadratic:
1 8 2
-0.256970 and -7.743030Square roots of this quadratic are:
你看到这种格式吗?为什么会这样?
#include <stdio.h>
#include <math.h>
float abs_value (float x);
float approx_sqrt (float x);
float solve_quadratic (float a, float b, float c);
// The main function prompts the user for 3 constant values to fill a quadratic
// ax^2 + bx + c
int main(void)
{
float a, b, c;
printf("Please, enter three constants of the quadratic: \n");
if (scanf ("%f %f %f", &a, &b, &c) == 3)
printf("Square roots of this quadratic are: \n", solve_quadratic(a,b,c));
return 0;
}
// Function to take an absolute value of x that is used further in square root function
float abs_value (float x)
{
if (x < 0)
x = - x;
return x;
}
// Function to compute an approximate square root - Newton Raphson method
float approx_sqrt (float x)
{
float guess = 1;
while (abs_value (pow(guess,2) / x) > 1.001 || abs_value (pow(guess,2) / x) < 0.999)
guess = (x / guess + guess) / 2.0;
return guess;
}
// Function to find roots of a quadratic
float solve_quadratic (float a, float b, float c)
{
float x1, x2;
float discriminant = pow(b,2) - 4 * a * c;
if (discriminant < 0)
{
printf("Roots are imaginary\n");
return -1;
}
else
{
x1 = (-b + approx_sqrt(discriminant)) / (2 * a);
x2 = (-b - approx_sqrt(discriminant)) / (2 * a);
}
return x1, x2;
}
谢谢!
答案 0 :(得分:2)
if (scanf ("%f %f %f", &a, &b, &c) == 1)
scanf
返回成功扫描的参数数量。在这种情况下,您希望它为3,而不是1。
答案 1 :(得分:2)
该行
return x1, x2;
不会返回两个值。该行相当于:
x1; // Nothing happens.
return x2;
如果您希望能够返回两个值,请创建struct
并返回struct
的实例。
typedef struct pair { float x1; float x2;} pair;
// Change the return type of solve_quadratic
pair solve_quadratic (float a, float b, float c);
准备好从solve_quadratic
返回时,请使用:
pair p;
p.x1 = x1;
p.x2 = x2;
return p;
并改变您使用它的位置:
// if (scanf ("%f %f %f", &a, &b, &c) == 1)
// ^^^ That is not correct.
if (scanf ("%f %f %f", &a, &b, &c) == 3)
{
pair p = solve_quadratic(a,b,c);
printf("Square roots of this quadratic are: %f %f \n", p.x1. p.x2);
}