Nikita
Nikita

Reputation: 33

How to keep repetition out in user-defined functions

After compiling, my GetInt function causes the printf statements within the function to be printed on the screen three times. I believe this was caused when I initialized all radius, base, and height to GetInt(void) but I see no other way of accurately initializing those variables. Please help!

#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);
}

Upvotes: 0

Views: 51

Answers (2)

AustinWBryan
AustinWBryan

Reputation: 3326

A rule of thumb is to avoid repeating yourself whereever possible and don't repeat yourself. Imagine you want to change from two new lines (\n\n) to three (\n\n\n)? You would need to make that change three times.

Looking at the bare bones of GetInt, you are printing a prompt, two new lines, get a value and returning it. Thus, we can write the new function like this:

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
}

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49896

GetInt asks for, and reads, 3 distinct values, yet returns only the last one, every time it is called.

I think what you really want is to have GetInt ask for and return just 1 value, either passing it the prompt to print or printing it before calling it.

Upvotes: 1

Related Questions