将值放入c中的数组

时间:2013-01-12 11:50:44

标签: c arrays file-io

我有一个程序,目前可以确定分子在特定速度和温度下的概率。它们需要打印到输出文件中,因为每次变量之一增加5 例如:

for
    (tempK=173;tempK<1173;tempK+=5)
        {
        power=(mass/(2*pi*k*tempK));
        prob = ((4*pi)*pow(power,threeovertwo))*(exp((-mass*(pow(speed,two))/(2*k*tempK))));

        fprintf (fp,"Molecular Name:%s Molecular Mass:%lg\n Probability: %lg Temperature:%lg Speed:%lg\n",name,mass,prob,tempK,speed);

这在一定程度上起作用,但唯一的问题是分子名称:和分子质量:在每一行之间重复,给出如下输出文件:

Molecular Name:Hydrogen Molecular Mass:2
 Probability: 0 Temperature:1158 Speed:50
Molecular Name:Hydrogen Molecular Mass:2
 Probability: 0 Temperature:1163 Speed:50
Molecular Name:Hydrogen Molecular Mass:2
 Probability: 0 Temperature:1168 Speed:50

哪个是不受欢迎的,有没有人知道如何阻止这种情况发生,可能是通过将所有变量('温度')等输入到数组中然后打印数组。

1 个答案:

答案 0 :(得分:1)

在循环外打印分子量和名称:

 fprintf (fp,"Molecular Name:%s Molecular Mass:%lg\n",name,mass);

 for(tempK=173;tempK<1173;tempK+=5)
 {
    power=(mass/(2*pi*k*tempK));
    prob = ((4*pi)*pow(power,threeovertwo))*(exp((-mass*(pow(speed,two))/(2*k*tempK))));

    fprintf (fp,"Probability: %lg Temperature:%lg Speed:%lg\n",prob,tempK,speed);
 }