我想写一个简单的程序来找出不同形状的区域。该程序编译得很好,但是当它运行时它不会给我正确的答案。我的意思是当它运行它时会问:如果用于字符串比较的语句没有正确执行
你想找什么区域?
,当我键入
方
或其他任何东西,然后回车,它只是结束,它不执行任何其他代码。
代码如下。
#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