Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the placement of variable declaration giving diffrent results?

#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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading