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

C语言实现指数分布MSE计算程序无输出,求问题排查

C语言指数分布MSE计算程序无输出问题排查

问题背景

编写C语言程序计算指数分布总体参数θ与不同样本量n对应的均方误差(MSE),程序无任何输出且无报错信息,原代码如下:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(void) 
{
  int n ,N=5;
  float theta,msum =0.0,mse; //paramters
  int i,j; // loop
  printf("Enter the value of n ");
  scanf("%d", &n);
  printf("Enter the value of theta ");
  scanf("%f ", &theta);
  
  //float u[n], x[n];
  
  //first we fix theta and find MSE for different values of n
  for(i=0;i<N;i++)
    {
      float sum = 0.0;
      for(j=0;j<n;j++)
        {
          //x[j] = (-1/theta)*log(1-(rand()/RAND_MAX));
          sum += (-1/theta)*log(1-(rand()/RAND_MAX)); //generates random number from unifrom dist and then converts it to exponential using inverse cdf function
          printf("%d%d", i, j);
        }
      float thetahat = n/sum;
      msum += (thetahat - theta)*(thetahat - theta);
    }
    mse = msum/N;
  printf("The MSE with n=%d and theta=%f is %f", n, theta, mse);
  
 
  return 0;
}

问题排查与修复

1. scanf格式符后多余空格导致程序阻塞

  • 问题:scanf("%f ", &theta);中%f后的空格会让scanf持续等待输入非空白字符,输入θ值后按回车,程序不会继续执行,而是卡在输入阶段,导致无输出。
  • 修复:删除%f后的空格,修改为scanf("%f", &theta);

2. 整数除法导致计算逻辑错误

  • 问题:rand()和RAND_MAX均为整数,rand()/RAND_MAX执行整数除法,结果恒为0,进而导致log(1-0)=log(1)=0,最终sum为0,后续thetahat = n/sum触发除零错误(部分环境会静默终止程序)。
  • 修复:将其中一个操作数转为浮点数,修改为(double)rand()/RAND_MAX,确保执行浮点除法。

3. 其他潜在优化点

  • 未初始化随机数生成器:添加srand((unsigned int)time(NULL));(需包含<time.h>头文件),保证每次运行生成不同的随机样本序列。
  • 浮点数精度:将float替换为double,提升计算精度,减少累积误差。
  • 可变长度数组(VLA):原代码中注释的float u[n], x[n];属于VLA,部分旧编译器不支持,若需使用可改用动态内存分配(malloc/free)。

修正后的完整代码

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>

int main(void) 
{
    int n, N = 5;
    double theta, msum = 0.0, mse;
    int i, j;

    printf("Enter the value of n: ");
    scanf("%d", &n);

    printf("Enter the value of theta: ");
    scanf("%f", &theta);

    // 初始化随机数生成器,保证每次运行样本不同
    srand((unsigned int)time(NULL));

    for(i = 0; i < N; i++)
    {
        double sum = 0.0;
        for(j = 0; j < n; j++)
        {
            double u = (double)rand() / RAND_MAX;
            sum += (-1.0 / theta) * log(1 - u);
        }
        double thetahat = (double)n / sum;
        msum += (thetahat - theta) * (thetahat - theta);
    }
    mse = msum / N;
    printf("The MSE with n=%d and theta=%.4f is %.4f\n", n, theta, mse);

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:33:30