2017-03-15 58 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