2017-03-15 21 views
-1

代码简介:这是一个二次方程计算器。它可以帮助你找到方程的根源。代码正在跳过程序中的命令。 (C)

代码:

#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语句来查看它是否会打印任何内容,但是跳过了这个语句。

输出我:

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 
+3

对于初学者,使用'=='进行比较,而不是'='! – Li357

+1

'dis = 0'应该是'dis == 0' –

回答

0

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

if(dis == 0) 

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

0

您使用的是运营商=当你想操作==

a == b检查2个数字是否相等,而a = b将第一个数值设置为第二个数值。

换言之,将dis = 0更改为dis == 0

+4

你应该评论和标记为印刷错误而不是回答。 – Li357