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

4szc88ey  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(111)
#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;
}

在第9到11行中,如果我在第二行或第三行(即第10行或第11行)声明float,则返回的最终值为197040072659526240000000000000000.000000,这不是我的期望值。但是,当我在第一行(即第9行)声明float变量时,返回的最终值为250.000000,这是我的期望值。

8wtpewkr

8wtpewkr1#

它应该是:

float tot_price = 0;

那么位置可能就不重要了。2就像现在一样,代码正在给未初始化的变量添加数字,这将不会有可预测的结果。

相关问题