Kurzbeschreibung des Codes: Es ist eine quadratische Gleichung Rechner. Es hilft Ihnen, die Wurzeln einer Gleichung zu finden.Code überspringt einen Befehl im Programm. (C)
Code:
#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;
}
}
}
Problem: Es funktioniert völlig in Ordnung, wenn die Diskriminante größer als Null ist. Aber wenn es gleich oder kleiner als Null ist, überspringt es aus irgendeinem Grund alles im Code. Ich habe Probleme, den Fehler zu finden. Ich habe eine printf-Anweisung geschrieben, um zu sehen, was der Wert der Diskriminante ist, und ich habe eine printf-Anweisung in der if-Anweisung gespeichert, um zu sehen, ob sie etwas druckt, aber das hat sie übersprungen.
Ausgang I bekam:
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
Ausgang Ich möchte:
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
Für den Anfang, verwenden Sie '==' zum Vergleich, nicht '='! – Li357
'dis = 0' sollte' dis == 0' sein –