gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:39:52 25 4
gpt4 key购买 nike

这是我的代码:

#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])开始,它输出了错误的数字。

我尝试将 k[] 替换为 const(例如 pow(lo,5)),结果是正确的。

有什么解决办法吗?

最佳答案

%d 不是 double 的正确 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 fscanf 函数/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

关于c - 在 pow() 中执行双数组时输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29531161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com