我遇到了这个程序输出的问题。它没有正确接收输入。我相信它可能与我的用户定义函数有关,它充当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;
}
答案 0 :(得分:8)
您可以尝试修改您的程序
int GetNum(void)
{
int num;
scanf("%d", &num);
return num;
}
答案 1 :(得分:2)
scanf("%d");
需要额外的参数。您需要为其提供您希望存储该数字的变量的地址。例如, scanf("%d",&length);
答案 2 :(得分:2)
主要问题是,GetNum函数根本不返回任何值:
int GetNum(void)
{
scanf("%d");
}
此外,在您对scanf的调用中,您忘记提供存储位置来存储扫描的号码(如果有的话)。
将其更改为:
int GetNum (void) {
int i;
scanf ("%d", &i);
return i;
}
应该或多或少地解决您的问题。要检查扫描是否成功,您可能还需要检查scanf的返回值 - 它应该返回成功解析的项目数(在您的情况下为1)。
BTW:使用正确的编译器切换像你这样的bug应该更容易发现。如果您正在使用gcc,那么开关-Wall会给您警告: main.c:12:警告:控制到达非空函数的结尾
答案 3 :(得分:-3)
在这种输入的情况下,我更喜欢使用iostream的功能,它更简单。
#include <stdio.h>
#include <math.h>
#include <iostream>
#define PI 3.14
using namespace std;
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");
cin >> length;
printf(" Please enter the width of a rectangle \n");
cin >> width ;
printf(" Please enter the radius of a circle \n");
cin >> radius ;
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;
}
另外,如果需要,您可以将输出设置为,例如
cout&lt;&lt; “请输入矩形的长度”&lt;&lt; ENDL;