Obada
Obada

Reputation: 43

Why do i need to typecast here?

So, I had a task in my C quiz to write a program that prompts the user to enter three integer values, then passes their addresses as pointers to a function that apply changes to these values according to some conditions, then send the average of these UPDATED values as a float.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

float Update(int *x, int *y, int *z);
int main()
{
    float avg;
    int x, y, z;
    printf("Please enter three intger values for x, y, and z respectively:");
    scanf("%d %d %d", &x, &y, &z);
    printf("\n\nthe values that you entered are:\n\tx = %d\n\ty = %d\n\tz = %d", x, y, z);
    avg = Update(&x, &y, &z);
    printf("\nthe UPDATED values are:\n\tx = %d\n\ty = %d\n\tz = %d", x, y, z);
    printf("\nthe average of the updated values are: %.1f\n\n", avg);
    system("pause");
    return 0;
}

float Update(int *x, int *y, int*z)
{
    float AVERAGE;
    if (*x % 2 == 0)    // for x
        *x *= 3;
    else
        *x -= 8;

    if (*y % 2 == 0)  // for y
        *y *= 3;
    else
        *y -= 8;

    if (*z % 2 == 0)  // for z
        *z *= 3;
    else
        *z -= 8;
    AVERAGE = (*x + *y + *z) / 3;
    return AVERAGE;
}

Entering 5, 10, 7 should give me an average of 8.0 instead of 8.7.
I know that (even though AVERAGE and avg are all float) typecasting solves it but why?

Upvotes: 0

Views: 65

Answers (1)

Yunnosch
Yunnosch

Reputation: 26703

Typecasting is not needed. You just need to make sure that integer division is avoided:

AVERAGE = ((*x)*1.0f + (*y)*1.0f + (*z)*1.0f) / 3;

This is more generously explicit (drawing attention to why it is done) than the shorter and probably more readable alternative solution by SomeProgrammerDude (which I include for completeness):

(*x + *y + *z) / 3.0f

Upvotes: 4

Related Questions