#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在第2行或第10行或第11行宣告,最終回傳的值為197040072659526240000000000000000.000000,這不是我期望的值。但是,當我float在第一行(即第 9 行)宣告變數時,回傳的最終值250.000000是我的預期值。
uj5u.com熱心網友回復:
它應該是:
float tot_price = 0;
那么位置可能無關緊要。和現在一樣,代碼將數字添加到未初始化的變數中,這不會有可預測的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/533773.html
標籤:C调试
