You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

变量声明位置为何导致C语言程序运行结果差异?

问题代码
#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;
}
问题描述

在上述代码的fracK函数第9至11行中,若将float类型变量tot_price声明在第10行或第11行,程序最终输出值为197040072659526240000000000000000.000000,与预期结果不符;但将其声明在第9行时,程序输出预期值250.000000,请问此现象的原因是什么?

原因分析
  • 这是C语言中局部自动变量未初始化导致的未定义行为:C语言规定,函数内声明的局部自动变量(无static修饰)如果没有显式初始化,其初始值是随机的垃圾值,取决于当前栈内存的状态,程序行为无任何保证。
  • 当tot_price声明在第9行时,它在used数组之前分配栈空间,而used数组随后被循环赋值为0,栈内存的偶然状态导致tot_price的初始垃圾值恰好为0,因此累加计算得到了正确结果——这只是巧合,不能作为合理依赖。
  • 当tot_price声明在第10或11行时,它的栈位置在used数组之后(或中间),初始垃圾值是一个极大的随机数,累加后就出现了错误的超大输出值。
正确解决方法

无论把tot_price声明在哪个位置,都必须显式初始化为0,写法如下:

float tot_price = 0.0f;

这样就能保证变量初始值正确,无论栈布局如何,程序都会输出预期的250.000000。

内容的提问来源于stack exchange,提问作者K___V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:15:40