在 pow() 中执行双数组时输出错误

Wrong output when doing double array in pow()

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
FILE *infile, *outfile;
int main(){
    double landa, mu, lo, blocking_prob[4], mean_arrival_rate,
           mean_service_rate, k[4], p[4];

    infile = fopen("mm1.in", "r");
    outfile = fopen("mm1.out", "w");

    fscanf(infile, "%d %d %d %d %d %d",
        &mean_arrival_rate, &mean_service_rate,
        &k[0],&k[1],&k[2],&k[3] );

    lo = mean_arrival_rate / mean_service_rate;

    fprintf(outfile,
        "Initial setting : mean_arrival_rate = %d , mean_service_rate = %d \n\n",
        mean_arrival_rate,mean_service_rate);
    for(int x=0;x<4;x++) {
        printf("%f \n",pow(lo,k[x]) );
        blocking_prob[x]= ( (1-lo)*pow(lo,k[x]) ) / (1- pow(lo,k[x]+1));
        fprintf(outfile,"Blocking Probability is %f when K = %d \n\n",
            blocking_prob[x],k[x]);
    }
}

输出从pow(lo,k[x])开始,输出错误的数字。

我尝试用 const 替换 k[](例如 pow(lo,5)),它是对的。

有什么解决办法吗?

%d 而不是 双精度的正确 scanf 格式说明符。您需要使用 %lf 而不是 1.

如果您在读入后打印出 k[] 的值,您会发现它们与您的预期大不相同。

例如,考虑以下程序:

#include <stdio.h>

int main (void) {
    double d1, d2;
    printf ("> ");
    scanf ("%lf %d", &d1, &d2); // one right, one wrong.
    printf ("Input was: %f %f\n", d1, d2);
    return 0;
}

运行 给你:

pax$ ./testprog
> 3.14159 2.71828
Input was: 3.141590 -0.000000

1 C11 7.21.6.2 The fscanf function /10 说得最好:

If [the object receiving the value] does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined

您需要为 double 使用 %lf 格式说明符,而不是 int

%d