Home > Blockchain >  Why is the placement of variable declaration giving different results?
Why is the placement of variable declaration giving different results?

Time:11-16

#include <stdio.h>

int order = 3;
int wt[10] = {2,1,3};
int price [10] = {100,50,150};
int maxW = 5;

void fracK() {
    int curr_weight, i, max_i;  // <<<<
    float tot_price;            // <<<<
    int used[10];               // <<<<

    //inititialising all used elements to 0
    for (i = 0; i < order;   i) {
        used[i] = 0;
    }

    curr_weight = maxW;

    while (curr_weight > 0) {
        max_i = -1;

        for (i = 0; i < order;   i) {
            if ((used[i] == 0) && ((max_i == -1) || ((float)price[i]/wt[i] > (float)price[max_i]/wt[max_i]))){
                max_i = i;
            }
        }
        used[max_i] = 1;
        curr_weight -= wt[max_i];
        tot_price  = price[max_i];

        if (curr_weight >= 0) {
            continue;
        }else {
            tot_price -= price[max_i];
            tot_price  = (1   (float)curr_weight/wt[max_i]) * price[max_i];
        }
    }
    printf("%f", tot_price);
}

//driver function
int main(int argc, char *argv[]) {
    fracK();
    return 0;
}

in lines 9 to 11, if I declare float in the second or third line i.e. line 10 or 11, the final value returned is 197040072659526240000000000000000.000000, which is not my expected value. However, when I declare the float variable in the first line, i.e. line 9, the final value returned is 250.000000 which is my expected value.

CodePudding user response:

It should be:

float tot_price = 0;

then the placement probably will not matter. As is now, the code is adding numbers to uninitialized variable, which will not have predictable results.

  • Related