[英]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;
}
在第 9 到 11 行中,如果我在第二行或第三行(即第 10 行或第 11 行)聲明float
,則返回的最終值為197040072659526240000000000000000.000000
,這不是我的預期值。 但是,當我在第一行(即第 9 行)聲明float
變量時,最終返回的值為250.000000
,這是我的預期值。
它應該是:
float tot_price = 0;
那么位置可能無關緊要。 和現在一樣,代碼將數字添加到未初始化的變量中,這不會有可預測的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.