如何在用户定义的函数中保持重复

时间:2016-02-13 02:39:05

标签: c

编译后,我的GetInt函数会使函数中的printf语句在屏幕上打印三次。我相信这是在我将所有半径,基数和高度初始化为GetInt(void)时引起的,但我看不到其他方法可以准确地初始化这些变量。请帮忙!

#define _CRT_SECURE_NO_WARNINGS
#define PI 3.14159
#include <stdio.h>
#include <math.h>

int GetInt(void);
double CalcTriangleArea(int base, int height);
double CalcCircleArea(int radius);

int main(void)
{
    int radius, base, height;
    double triangleArea;
    double circleArea;

    radius = GetInt();
    base = GetInt();
    height = GetInt();
    triangleArea = CalcTriangleArea(base, height);
    circleArea = CalcCircleArea(radius);

    return(0);
}

int GetInt(void)
{
    int x;

    {
        printf("Please enter a radius: \n\n");
        scanf("%d", &x);

        printf("Please enter a base: \n\n");
        scanf("%d", &x);

        printf("Please enter a height: \n\n");
        scanf("%d", &x);
    }
    return(x);
}

double CalcTriangleArea(int base, int height)
{
    double triangleArea;
    printf("Triangle area is %.2f \n\n", triangleArea = .5*base*height);

    return(0);
}

double CalcCircleArea(int radius)
{
    double circleArea;
    printf("Area is %.4f \n\n", radius, circleArea = PI * pow(radius, 2));

    return(0);
}

2 个答案:

答案 0 :(得分:1)

GetInt要求并读取3个不同的值,但每次调用时都只返回最后一个值。

我认为你真正想要的是让GetInt请求并返回1个值,或者在调用它之前将其提示打印或打印它。

答案 1 :(得分:1)

经验法则是尽量避免重复自己,不要重复自己。想象一下,您想要从两个新行(\n\n)更改为三个(\n\n\n)?您需要进行三次更改。

查看GetInt的简单骨骼,您将打印一个提示符,两个新行,获取一个值并返回它。因此,我们可以像这样编写新函数:

void getInt(char* prompt)
{
    int x, numberOfConversions;               // numConversions is the number of int's read from the keyboard buffer

    printf("%s: \n\n", prompt);
    numberOfConversions = scanf("%d", &x);

    while (numberOfConversions != 1)          // while the user did not enter a number
    {
        printf("Please enter a number: ");
        numberOfConversions = scanf("%d", &x)"
    }

    return x;                                 // Always returns a valid number
}