简体   繁体   English

为什么变量声明的位置会给出不同的结果?

[英]Why is the placement of variable declaration giving different 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 ie line 10 or 11, the final value returned is 197040072659526240000000000000000.000000 , which is not my expected value.在第 9 到 11 行中,如果我在第二行或第三行(即第 10 行或第 11 行)声明float ,则返回的最终值为197040072659526240000000000000000.000000 ,这不是我的预期值。 However, when I declare the float variable in the first line, ie line 9, the final value returned is 250.000000 which is my expected value.但是,当我在第一行(即第 9 行)声明float变量时,最终返回的值为250.000000 ,这是我的预期值。

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.和现在一样,代码将数字添加到未初始化的变量中,这不会有可预测的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM