c-double的输入不正确事件houg转换器不正确



我一直在努力解决以下程序,该程序帮助我在数学课上计算二次方程时作弊:

/*Improved version of my maths cheat code -w-,
this program has the same functionality as the last but with
cleaner and more correct code. Notes taken from the post made in
codereview.stackechange to make it less of a dumpster fire.
The program is not functional already.*/
#include<stdio.h>
#include<math.h>
double a,b,c,d;
//Get values of the equation
void get_values (void){
printf("Dame el valor de a: ");
scanf("%g", &a);
printf("Dame el valor de b: ");
scanf("%g", &b);
printf("Dame el valor de c: ");
scanf("%g", &c);
}
//Calculates the discriminante
double discriminante (double a, double b, double c){
double result;
result = b*b-4*a*c;
return result;
}
//Prints the result of the equation based on the square root
//of the discriminate
void display (double d){
if (d>0){
printf("El resultado es: (%g±%g)/%gn", -b, sqrt(d), a*2);
}
else if (d<0){
printf("El resultado es: (%g±%gi)/%gn", -b, sqrt(-d), a*2);
}
else { // d == 0
printf("El resultado es: %g/%gn", b, a*2);
}
}
int main(){
get_values();
d = discriminante(a,b,c);
printf("El valor del discriminante es: %gn",d);
display(d);
return 0;
}

我在codereview.stackeexchange上发了一篇帖子,以获得对我的代码的一些反馈。在用一种更干净、通常更好的方式重写了这个东西之后,我发现了一个小问题,即函数从来没有正确地接受输入。我已经检查了scanf和转换器一个小时了,在这一点上,我很困惑为什么它拒绝正确输入。我是使用了不正确的转换器,还是在discriminante上出错?

scanf()中的%g用于读取float。您应该使用%lg来读取double

注意,在printf()中使用%g来打印double是可以的。

最新更新