我正在尝试编写一个简单的程序来查找不同形状的区域。程序编译得很好但是当它运行时它没有给我正确的答案。我的意思是当它运行时问:
你想找到哪个区域?
当我输入
方
或其他任何内容并点击输入它刚刚结束,它不执行任何其他代码。
代码如下。
#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;
}
答案 0 :(得分:1)
您的代码中存在许多错误。字符串使用strcmp
而非==
你的
if(yourchoice[40]== 'square')
应该是
if(0 == strcmp(yourchoice, "square"))
答案 1 :(得分:1)
您无法将C字符串与==
进行比较。您需要strcmp()
。 ''
用于单个字符,而不是字符串。
所以,改变
if(yourchoice[40]== 'square')
到
if( !strcmp(yourchoice, "square"))
和
else if(yourchoice== 'rectangle')
到
else if(!strcmp(yourchoice, "rectangle"))
顺便说一下,您需要为<string.h>
strcmp()
另外,更改
printf("Area of the Square is %f",&Sq);
到
printf("Area of the Square is %f", Sq);
^
no need of &
和
printf("Area of the Rectangle : %f ",&Rec);
到
printf("Area of the Rectangle : %f ",Rec);
当您将&
放在标识符之前时,它会返回该标识符的地址。您无需在&
printf()
答案 2 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
using namespace std;
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);
//Here, strcmp is the prefered way to compare the strings
//string.h is the header to use it
// It returns 0 when the string match
//if(yourchoice == 'square'){
if(!strcmp(yourchoice,"square")){
printf("Length of any side of the square =");
scanf(" %f",&a);
Sq = pow(a,2);
//Second correction: & are to used only when storing the input and not while accessing or displaying it.So, in scanf you have to use but not for printf statements
printf("Area of the Square is %f",Sq);
}
else if(!strcmp(yourchoice,"rectangle"))
{
printf("Height = \n");
//Third Correction, in the org code you had missed to write "&" before the variable 'a'
scanf("%f",&a);
printf("Width=\n");
//Fourth Correction, in the org code you had missed to write "&" before the variable 'b'
scanf("%f",&b);
Rec= a*b;
//Fifth correction: Same as second correction. Not to use '&' sign in printf statements
printf("Area of the Rectangle : %f ",Rec);
}
return 0;
}