#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 行中,如果我float在第二行或第三行,即第 10 行或第 11 行中宣告,則回傳的最終值為197040072659526240000000000000000.000000,這不是我的預期值。但是,當我float在第一行(即第 9 行)宣告變數時,回傳的最終值250.000000就是我的預期值。
uj5u.com熱心網友回復:
它應該是:
float tot_price = 0;
那么位置可能無關緊要。就像現在一樣,代碼正在向未初始化的變數添加數字,這不會產生可預測的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/531724.html
標籤:C调试
上一篇:Angular'nativeElement viewchild'vs'document.querySelector'相當混亂
