[英]Issue with a program in C not correctly receiving the input
我遇到了這個程序輸出的問題。 它沒有正確接收輸入。 我相信它可能與我的用戶定義函數有關,它充當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;
}
您可以嘗試修改您的程序
int GetNum(void)
{
int num;
scanf("%d", &num);
return num;
}
scanf("%d");
需要額外的論據。 你需要給它一個你希望存儲數字的變量的地址。例如scanf("%d",&length);
主要問題是,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:warning:control到達非void函數的結尾
在這種輸入的情況下,我更喜歡使用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 <<“請輸入矩形的長度”<< endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.