请看一下我在第七章C编程之后作为赋值的一部分写的程序,该程序应该根据用户键入的常量的值返回二次方的根。这个程序应该很简单,我是初学者。尽管编译器确实编译了程序,但我得到的唯一输出是提示消息。但是在我输入了三个值之后,什么也没有发生,程序结束,我回到了我的终端。我已经编辑了这个程序。现在,如果我输入一些使判别式小于0的值,我会得到
Please, enter three constants of the quadratic:
1 2 3
Roots are imaginary
Square roots of this quadratic are:因此,main function语句仍然出现。
如果我输入其他值,我会得到
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;
}谢谢!
发布于 2015-10-01 01:11:39
if (scanf ("%f %f %f", &a, &b, &c) == 1)scanf返回扫描成功的参数个数。在本例中,您希望它是3,而不是1。
发布于 2015-10-01 01:17:21
这条线
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);
}https://stackoverflow.com/questions/32871968
复制相似问题