gpt4 book ai didi

代码正在跳过程序中的命令。 (C)

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

代码简要说明:这是一个二次方程计算器。它可以帮助您找到方程的根。

代码:

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

main(){
int a, b, c, real;
float root1, root2, img, dis;
char solve;

printf("Do you want to solve an equation (y/n): ");//Ask user if they want to solve an equation
scanf("%c", &solve);

if(solve == 'n'){//Terminate program
return 0;
}

if(solve == 'y'){//Code for calculation
printf("\nInput the number");
printf("\n````````````````");
printf("\nA: ");//Store number for a, b, c for the quadratic formula
scanf("%d", &a);
printf("\nB: ");
scanf("%d", &b);
printf("\nC: ");
scanf("%d", &c);

dis = (b*b) - (4*a*c);//calculation for the discriminent

//printf("%f", dis); Check the discriminant value

if(dis > 0){//Calculation for the real root
root1 = ((b*-1) + sqrt(dis))/(2*a);
root2 = ((b*-1) - sqrt(dis))/(2*a);

printf("\nRoot 1: %.2f", root1);
printf("\nRoot 2: %.2f", root2);

return 0;
}

if(dis = 0){//Calculation for no discriminent
root1 = (b*-1)/(2*a);
printf("\nRoot 1 and 2: %.2f", root1);
return 0;
}

if(dis < 0){//Calculation for complex root
dis = dis * -1;

//printf("\n%f", dis); !!!Testing to see why the code isn't functioning!!! It skipped this

root1 = (b*-1)/(2*a);
img = (sqrt(dis))/(2*a);

printf("Root 1 and 2: %.2f ± %.2f", root1, img);

return 0;
}
}
}

问题:如果判别式大于零,它就可以正常工作。但是当它等于或小于零时,它会出于某种原因跳过代码中的所有内容。我很难找到错误。我放入 printf 语句来查看判别式的值是多少,并且在 if 语句中保留了 printf 语句以查看它是否会 printf 任何内容,但它跳过了这一点。

我得到的输出:

gcc version 4.6.3
Do you want to solve an equation (y/n): y

Input the number
````````````````
A: 1
B: 2
C: 5 //It ends here

我想要的输出:

gcc version 4.6.3
Do you want to solve an equation (y/n): y

Input the number
````````````````
A: 1
B: 2
C: 5
Root 1 and 2: -1±2i

最佳答案

如果您查看 dis = 0if 语句,它应该:

if(dis == 0)

这应该可以解决你的所有问题。代码做得很好。只是一个初学者的错误。

关于代码正在跳过程序中的命令。 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42821513/

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