Variables aren't initialized as expected

ghz 8months ago ⋅ 75 views

I have a persistent question that I haven't found an answer to yet. Why is the last variable in example 1 not initialized with the value that was entered, while in example 2 this is the case?

EXAMPLE 1:

#include <stdio.h>

int main(){
    float a, b, c, average = scanf("%f %f %f", &a, &b, &c);

    average = (a * 2 + b * 3 + c * 5) / 10;

    printf("AVERAGE = %.1f\n", average);

    return 0;
}

EXAMPLE 2:

#include <stdio.h>

int main(){
    float a, b, c = scanf("%f %f %f", &a, &b, &c);

    float average = (a * 2 + b * 3 + c * 5) / 10;

    printf("AVERAGE = %.1f\n", average);

    return 0;
}

I tried assigning three prompt-typed values to the variables in example 2, but the last variable always stores an incorrect value. This changes when I declare a fourth variable -- average -- on the same line without assigning a value to it.

Answers

In both examples, you are trying to assign the result of the scanf function directly to a variable. However, the scanf function returns the number of input items successfully matched and assigned, not the actual input values. Therefore, the behavior you are observing is not related to the initialization of the last variable but rather to how scanf works.

Let's break down the behavior in each example:

Example 1:

float a, b, c, average = scanf("%f %f %f", &a, &b, &c);

In this example, you declare a, b, c, and average as float variables. However, average is initialized with the return value of the scanf function, which is the number of input items successfully matched and assigned. Therefore, average will not contain the average of the input values but rather the number of successful assignments, which is 3 in this case.

Example 2:

float a, b, c = scanf("%f %f %f", &a, &b, &c);

In this example, you declare a, b, and c as float variables. However, you are again initializing c with the return value of the scanf function, which is the number of input items successfully matched and assigned. As a result, c will not contain the value you entered but rather the number of successful assignments, which is 3.

To correctly read the input values and calculate the average, you should separate the scanf function call from the variable initialization, like this:

#include <stdio.h>

int main() {
    float a, b, c;
    scanf("%f %f %f", &a, &b, &c);

    float average = (a * 2 + b * 3 + c * 5) / 10;

    printf("AVERAGE = %.1f\n", average);

    return 0;
}

This way, the scanf function reads the input values into a, b, and c, and then you can calculate the average using these values.