C语言中的程序未正确接收输入时出现问题

C语言中的程序未正确接收输入时出现问题,c,function,C,Function,我对这个程序的输出有问题。它没有正确地接收输入。我相信这可能与我的用户定义函数有关,该函数充当scanf #include <stdio.h> #include <math.h> #define PI 3.14 int GetNum(void) { return scanf("%d"); } int CalculateAreaR(int length, int width) { return length*width; } double Ca

我对这个程序的输出有问题。它没有正确地接收输入。我相信这可能与我的用户定义函数有关,该函数充当scanf

#include <stdio.h>
#include <math.h>
#define PI 3.14


int GetNum(void)
{
    return scanf("%d");
}

int CalculateAreaR(int length, int width)
{   
    return length*width;
}

double CalculateAreaC(int radius)
{
    return PI*radius*radius;
}

int main(void)
{
    int length;
    int width;
    int radius;
    int areaR;
    double areaC;

    printf( " Please enter the length of a rectangle  \n");
    length = GetNum();
    printf(" Please enter the width of a rectangle \n"); 
    width = GetNum();
    printf(" Please enter the radius of a circle \n");
    radius = GetNum();

    areaR = CalculateAreaR(length, width);

    printf("\nThe area of the rectangle is %d\n", areaR);

    printf("\nThe length is %d, the width is, %d and thus the area of the rectangle is %d\n\n", length, width, areaR);

    areaC = CalculateAreaC(radius);

    printf("\nThe area of the circle is %.3f\n", areaC);

    printf("\n\n The radius of the circle is %d and the area of the circle is %.3f\n\n", radius, areaC);

    return 0;
}
#包括
#包括
#定义PI 3.14
int GetNum(void)
{
返回扫描量(“%d”);
}
整数计算器EAR(整数长度、整数宽度)
{   
返回长度*宽度;
}
双计算EAC(整数半径)
{
返回PI*半径*半径;
}
内部主(空)
{
整数长度;
整数宽度;
整数半径;
国际区域;
双区;
printf(“请输入矩形的长度\n”);
length=GetNum();
printf(“请输入矩形的宽度\n”);
宽度=GetNum();
printf(“请输入圆的半径\n”);
radius=GetNum();
面积=计算面积(长度、宽度);
printf(“\n矩形区域为%d\n”,areaR);
printf(“\n长度为%d,宽度为%d,因此矩形的面积为%d\n\n”,长度、宽度、面积r);
面积c=计算面积eac(半径);
printf(“\n圆的面积为%.3f\n”,区域C);
printf(“\n\n圆的半径为%d,圆的面积为%.3f\n\n”,半径,面积为C);
返回0;
}

您可以尝试按以下方式修改您的程序

int GetNum(void)
{ 
   int num;
   scanf("%d", &num);

   return num;

}
scanf(“%d”)需要一个附加参数。您需要给它一个您希望在其中存储数字的变量的地址。e、 g.
scanf(“%d”和长度)

主要问题是,GetNum函数根本不返回任何值:

int GetNum(void)
{
  scanf("%d");
}
此外,在呼叫scanf时,您忘记提供存储扫描号码(如果有)的内存位置

将其更改为:

int GetNum (void) {
  int i;
  scanf ("%d", &i);
return i;
}
应该或多或少地解决你的问题。要检查扫描是否成功,您可能还需要检查scanf的返回值-它应该返回成功解析的项目数(在您的情况下为1)

顺便说一句:使用正确的编译器开关会更容易发现像你这样的错误

如果您使用gcc,开关墙会给您警告:
main.c:12:警告:控件到达非void函数的末尾

为编译器启用警告,应该是清楚的。您应该希望看到
警告:控件达到非无效函数的结尾
(或类似)。谢谢!你能解释一下为什么原来的函数不起作用吗?在原来的程序中,scanf需要一个参数来读取数据,而这个参数丢失了。增加了一点:如果代码写为
returnscanf(“%d”,&num)将返回1,即读取的参数数。因此,返回读取的数字很重要,即
num
scanf
也可以返回0或
EOF