gpt4 book ai didi

c - 没有指针的指针错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:23 25 4
gpt4 key购买 nike

我正在制作一个 C 程序,它读取圆形、正方形或三角形,并根据用户输入计算面积。我是用结构做的。我收到一些运行时错误和一些编译器错误。

每当我执行时,三角形选项就来了,而且面积不对。我尝试刷新输入缓冲区,但它仍然发生,这是为什么?

即使它编译编译器告诉我:“警告:赋值从指针生成整数而不进行强制转换[默认启用]。

这是什么意思,如何解决?另外这个程序中的指针在哪里,因为它对我来说不是很明显/

 #include <stdio.h>

struct point { int x, y; };

struct shape {
char shape_kind;
struct point centre;
float area;
union{
struct{
int height;
int width;
} rectangle;

struct{
int height;
int width;
} orthogonal_triangle;

struct{
int radius;
} circle;
}u;
};
int areaCalc(struct shape s, char shape_kind);

struct shape s;

int main(shape_kind){
fseek(stdin,0,SEEK_END);


printf("\nWould you like to calulcate the area of a Triangle, Rectangle, or Circle?\n");
scanf("%s", &shape_kind);

fseek(stdin,0,SEEK_END);


if((shape_kind = "Triangle") || (shape_kind = "triangle")){
printf("\nYou have selected Triangle. Please enter the base, followed by the height.\n");
scanf("%d",&s.u.orthogonal_triangle);
scanf("%d",&s.u.orthogonal_triangle);
}

else if((shape_kind = "Rectangle") || (shape_kind = "rectangle")){
printf("\nYou have selected Rectangle. Please enter the width followed by the height.\n");
scanf("%d",&s.u.rectangle.width);
scanf("%d",&s.u.rectangle.height);
}

else if((shape_kind = "Circle") || (shape_kind = "circle")){
printf("\nYou have entered Circle. Please enter the radius. \n");
scanf("%d", &s.u.circle.radius);
}

else{
printf("\nI am sorry, but your input could not be read. Please try again.\n");
main();
}

areaCalc(s,shape_kind);
return 0;
}

int areaCalc(struct shape s, char shape_kind){
if((shape_kind = "Rectangle") || (shape_kind = "rectangle")){
s.area = s.u.rectangle.height*s.u.rectangle.width;
}

else if((shape_kind = "Triangle") || (shape_kind = "triangle")){
s.area = s.u.orthogonal_triangle.height *1/2*s.u.orthogonal_triangle.width;
}

else if((shape_kind = "Circle") || (shape_kind = "circle")){
s.area = s.u.circle.radius*s.u.circle.radius*3.1415926235;
}

else{
printf("\nI'm sorry your input could not be read, please try again.\n");
main();
}

printf("The total area of the %s is %f", shape_kind, s.area);

return 0;
}

最佳答案

有几个错误:

  1. 如果您想scanf()一个像“Triangle”或“Circle”这样的字符串,您需要一个数组:

     char shape_kind[80];
    ...
    scanf( "%s" shape_kind );
    /* or safer: */
    scanf( "%79s", shape_kind );
  2. 您不能将字符串与 = 进行比较。那是一个赋值(我想这些是导致编译器警告的行)。您可以使用 == 来比较整数,但对于字符串,您需要 strcmp():

    if( strcmp( shape_kind, "Triangle" ) == 0 )
    ....

顺便说一句:下次,请正确缩进您的代码,如果您有编译错误或警告,请告诉我们它们出现的行

关于c - 没有指针的指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22011593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com