gpt4 book ai didi

c - 为什么程序输出x1 = Nan,x2 = Nan?

转载 作者:行者123 更新时间:2023-11-30 20:36:24 25 4
gpt4 key购买 nike

我不明白为什么我的程序没有做它应该做的事情。任务是编写一个可以使用两个 c 文件求解二次方程的 c 程序。这是我们要使用的名为 interface.c 的代码,无需对此进行任何更改:

#include <stdio.h>

void abc (void);

int a, b, c;

extern double x1real, x1imag, x2real, x2imag;

static void get_parameters (void)
{
scanf("%d", &a);
scanf("%d", &b);
scanf("%d", &c);
}

void print_solution(void)
{
printf("The roots of %dx^2 + %dx + %d are:\n",a,b,c);

if(x1imag == 0 && x2imag == 0)
{
if(x1real == x2real)
{
printf("x = %.4f\n", x1real);
}
else
{
printf("x1 = %.4f, x2 = %.4f\n", x1real, x2real);
}
}
else
{
printf("x1 = %.4f+%.4fi, x2 = %.4f-%.4fi\n", x1real, x1imag, x2real, x2imag);
}
}

int main (void)
{
int runs, run;

scanf("%d",&runs);

for(run=0; run < runs; run++)
{
get_parameters();
abc();
print_solution();
}

return 0;
}

接下来是我编写的代码,它不起作用,我认为整数类型似乎出了问题。对于每个二次公式,它将输出 x1 = nan x2 = nan。整数类型有问题,但无法找出问题所在。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

extern int a, b, c;

double x1real, x1imag, x2real, x2imag;

int discriminant(void)
{
int discriminant;

discriminant = (pow(b,2)-4*a*c);

return discriminant;
}

void abc (void)
{
if (discriminant() > 0)
{
x1real = (-b - sqrt(discriminant()))/(2*a);
x2real = (-b + sqrt(discriminant()))/(2*a);
x1imag = 0;
x2imag = 0;
}
else
{
x1real = x2real = (-b) / (2*a);
x1imag = (-b - sqrt(-discriminant())) / (2*a);
x2imag = (-b + sqrt(-discriminant())) / (2*a);
}

return;
}
input:
4
2 0 0
1 3 2
3 4 9
1 0 1



output:
The roots of 2x^2 + 0x + 0 are:
x = 0.0000
The roots of 1x^2 + 3x + 2 are:
x1 = -1.0000, x2 = -2.0000
The roots of 3x^2 + 4x + 9 are:
x1 = -0.6667+-2.2653i, x2 = -0.6667-0.9319i
The roots of 1x^2 + 0x + 1 are:
x1 = 0.0000+-1.0000i, x2 = 0.0000-1.0000i

suspected output:
The roots of 2x^2 + 0x + 0 are:
x = 0.0000
The roots of 1x^2 + 3x + 2 are:
x1 = -1.0000, x2 = -2.0000
The roots of 3x^2 + 4x + 9 are:
x1 = -0.6667+1.5986i, x2 = -0.6667-1.5986i
The roots of 1x^2 + 0x + 1 are:
x1 = 0.0000+1.0000i, x2 = 0.0000-1.0000i

最佳答案

二次公式?

没有调用「b^2-4ac≧0」的条件表达式,是吗?

int discriminant(void)
{
int discriminant;

discriminant = (pow(b,2)-4*a*c);

return discriminant;
}

void abc (void)
{

// if (discriminant > 0) // it doesn't call [int discriminant(void)]
if (discriminant() >= 0)
{
x1real = (-b - sqrt(discriminant()))/(2*a);
x2real = (-b + sqrt(discriminant()))/(2*a);
x1imag = 0;
x2imag = 0;
}
else
{
x1real = x2real = (-b) / (2*a);
x1imag = (-b - sqrt(-discriminant())) / (2*a);
x2imag = (-b + sqrt(-discriminant())) / (2*a);
}

return;
}

(补充)

static void get_parameters (void)
{
do {
scanf("%d", &a);
scanf("%d", &b);
scanf("%d", &c);
} while(a == 0)
}

关于c - 为什么程序输出x1 = Nan,x2 = Nan?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36158645/

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