我想寫一個簡單的程序來找出不同形狀的區域。該程序編譯得很好,但是當它運行時它不會給我正確的答案。我的意思是當它運行它時會問:如果用於字符串比較的語句沒有正確執行
你想找什麼區域?
,當我鍵入
方
或其他任何東西,然後回車,它只是結束,它不執行任何其他代碼。
代碼如下。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
char yourchoice[40]="";
float a=0;; //a=height
float b=0; //b=breadth
float Sq,Rec,Parall,trap,cir,ell,tri;
printf("Here You can find out areas of Square,Rectangle,Parallelogram,trapezoid,circle,ellipse and triangle \n\n\n");
printf("what do u want to find area of? : \n");
scanf(" %s",yourchoice);
if(yourchoice[40]== 'square'){
printf("Length of any side of the square =");
scanf(" %f",&a);
Sq = pow(a,2);
printf("Area of the Square is %f",&Sq);
}else if(yourchoice== 'rectangle')
{
printf("Height = \n");
scanf("%f",a);
printf("Width=\n");
scanf("%f",b);
Rec= a*b;
printf("Area of the Rectangle : %f ",&Rec);
}
return 0;
}
我從來不明白的是爲什麼類在C使用字符串I/O第一初學者。有沒有什麼開始與哪個更適合?畢竟,它是一種系統編程語言,而不是一些通用的高級應用程序語言。那麼爲什麼要在一開始就打擾字符串呢? – BitTickler
另請參見:刪除關於此行的'printf'語句 – Keith
中的'&':'char yourchoice [40] =「」;'這導致您的選擇包含:'\ 0'。 + 30個字節的垃圾。一個更好的初始化將是:char yourchoice [40] = {'\ 0'};它用'\ 0'(NUL)字符填滿你的選擇。 – user3629249