我寫這個代碼來找到二次方程的根。它似乎工作,除非我在掃描部分之前放置一個空格。 (例如在我寫的輸入中:a=1,b=2, c=1
)。在這種情況下,它只是刪除變量。 (在這個例子中,我給c
將被從輸入中刪除,因此我收到的答案是0,-2而不是-1。)。如果我將空間放在其他地方(a =1,b= 2,c=1
),代碼將起作用。scanf在C空間導致刪除
我該如何解決這個問題?
int main()
{
double root1 = 0, root2 = 0;
double a = 0., b = 0., c = 0.;
printf("Enter a polynomial:\n");
scanf("a=%lf,b=%lf,c=%lf", &a, &b, &c);
{
if (a == 0)
{
return 0;
}
if ((b * b - 4 * a * c) == 0)
{
root1 = -b/2 * a;
printf("root is %f", root1);
}
else if ((b * b - 4 * a * c) < 0)
{
printf("There are no roots");
}
else {
root1 = (-b + sqrt(b * b - 4 * a * c))/2* a;
root2 = (-b - sqrt(b * b - 4 * a * c))/2* a;
printf("Roots are %f,%f", root1, root2);
}
}
return 0;
}
只是輸入1,2,1,然後輸入 –
由於前導空格是不是你的格式字符串的一部分。 –
忘記那些愚蠢的逗號和嚴格的輸入規格,只是不要輸入任何內容。 'printf(「輸入多項式a b c:\ n」); scanf(「%lf%lf%lf」,&a,&b,&c);'然後輸入'1 2 1'或用'newline'分隔。 –