![](/img/trans.png)
[英]My program exit without running any coded functions even though it doesn't return any error (C Language)
[英]Solve quadratic; learning functions; program doesn't return values
请看一看我在第7章“用C编程”之后编写的程序,该程序应根据用户键入的常量值返回二次方的根。 该程序应该非常简单。 我是初学者。 尽管编译器确实会编译程序,但我得到的唯一输出是提示消息。 但是,在输入三个值之后,什么也没有发生,程序结束了,回到了终端。 我已经编辑了程序。 现在,如果我输入一些使判别式小于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;
}
谢谢!
if (scanf ("%f %f %f", &a, &b, &c) == 1)
scanf
返回成功扫描的参数数量。 在这种情况下,您希望它是3,而不是1。
线
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.