gpt4 book ai didi

c - 求解二次;学习功能;程序不返回值

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:09 25 4
gpt4 key购买 nike

请看一下我在第 7 章 C 编程之后作为作业的一部分编写的程序。该程序应根据用户输入的常量值返回二次的根。该程序应该非常简单;我处于初学者水平。虽然编译器确实编译了程序,但我得到的唯一输出是提示信息。但是在我输入三个值之后,没有任何反应,程序结束,我又回到了我的终端。我已经编辑了程序。现在,如果我输入一些使判别式小于 0 的值,我会得到

Please, enter three constants of the quadratic:   
1 2 3
Roots are imaginary
Square roots of this quadratic are:

这样main函数语句还是出现了。

如果我输入其他值,我会得到

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。

关于c - 求解二次;学习功能;程序不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32871968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com