我是初学程序员,我有一个类分配,我应该从文件中读取信息,然后操纵该数据并将其写入另一个文件。 我得到了要打印的输出文件,但不是我计算的值,而是返回Nan。我不确定是不是因为它没有从输入文件中读取值,或者我的循环没有正常工作。
非常感谢任何帮助!
void linreg(ifstream &fin, double &m, double &b, double &r, double &firstx,
double &lastx)
{
// 1) reduction variable initialization
double sumx, sumy, sumxx, sumxy, sumyy, x, y;
sumx = 0;
sumy = 0;
sumxx = 0;
sumxy = 0;
sumyy = 0;
// 2) loop forever
for(;;)
{
// 3) attempt to input an ordered pair
fin >> x >> y;
// 4) test for end of file
if(fin.eof())
{
// 5) leave when true
break;
}
else
{
continue;
}
// 6) test for first iteration
if(n==0)
{
// 7) save lower limit of integration
x = firstx;
}
// 8) save upper limit of integration
else{
x = lastx;
}
// 9) update reduction variables
sumx = sumx + x;
sumy = sumy + y;
sumxx = sumxx + x * x;
sumxy = sumxy + x * y;
sumyy = sumyy + y * y;
}
// 10) calculate slope, y intercept and correlation coefficient
m = ((sumx * sumy) - (n * sumxy)) / ((sumx * sumx) - (n * sumxx));
b = (sumy - (m * sumx)) / n;
r = ((n * sumxy) - (sumx * sumy)) / (sqrt(((n * sumxx) - (sumx * sumx))*
((n * sumyy) - (sumy * sumy))));
}
另外,如果我的代码难以阅读,我很抱歉,我还在学习!
答案 0 :(得分:0)
else { continue; }
子句会跳过循环的其余部分。该行以下没有任何内容被执行。
现在,通常,编译器会发出警告,告诉您if(n==0)
是无法访问的代码,这意味着它永远不会被执行。
您没有看到此警告的事实意味着您尝试在未启用警告的情况下进行编程。不要试图这样做,它不会有任何好处。尝试使用-Wall
开关进行编译,或查看编译器的文档以了解如何启用所有警告。
修改强>
此外,您执行fin >> x >> y;
然后if(fin.eof())
,但这不起作用:您必须首先检查EOF,然后从流中读取。
此外,if(n==0) { x = firstx; } else { x = lastx; }
将始终用某些内容覆盖x
,这可能不是您想要做的,但我不知道您想要做什么
答案 1 :(得分:0)
您的代码将中断或继续每次迭代
if(fin.eof())
{
// 5) leave when true
break;
}
else
{
continue;
}