这是一个简单的C ++程序,它使用公式为两个给定数字之间的固定数量的值计算f(x)。
在for循环中,当k = 0时似乎存在一些问题。它正在返回垃圾值。
谁能告诉我为什么?
非常感谢您的帮助。预先感谢。
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main ()
{
int const POINTS = 21;
double const PI = 3.1416;
double min, max, increment, dataPoints[21];
cout << "Enter max value: ";
cin >> max;
cout << "Enter min value: ";
cin >> min;
increment = (max - min) / (POINTS - 1);
cout << setw (20) << "X-Value" << "|";
cout << setw (20) << "Y-Value" << endl;
double k;
int l;
for (k = min, l = 0; l < POINTS, k <= max; l++, k += increment)
{
dataPoints[l] = (PI / 16) * sin (6.036 * k) + (1 / 64) * PI * cos (24.44 * k);
cout << setw (20) << k << setw (20) << dataPoints[l] << endl;
}
}
输出:
Enter max value: 4
Enter min value: -4
X-Value| Y-Value
-4 0.164018
-3.6 -0.0507715
-3.2 -0.0881608
-2.8 0.182492
-2.4 -0.184497
-2 0.0931637
-1.6 0.0453027
-1.2 -0.16085
-0.8 0.195021
-0.4 -0.130529
-5.55112e-016 -6.57901e-016
0.4 0.130529
0.8 -0.195021
1.2 0.16085
1.6 -0.0453027
2 -0.0931637
2.4 0.184497
2.8 -0.182492
3.2 0.0881608
3.6 0.0507715
4 -0.164018
Process returned 0 (0x0) execution time : 3.634 s
Press any key to continue.
一个问题是代码(1 / 64)
...,因为您已将此表达式放在方括号中。因此,它是integer除法,因此,always的值将为zero。
尝试此,改为:
dataPoints[l] = (PI / 16) * sin (6.036 * k) + (1.0 / 64) * PI * cos (24.44 * k);
for
循环中表达“测试”条件的方式也存在问题-这里的comma operator实际上将忽略表达式的第一部分:
for (k = min, l = 0; l < POINTS, k <= max; l++, k += increment)
出于安全考虑,当您要测试both]条件时,请使用&&
运算符:
问题:for (k = min, l = 0; l < POINTS && k <= max; l++, k += increment) {
最后,您的actual
为在for循环中,当k = 0时似乎存在一些问题。它是返回垃圾值。
不,不是!您对
k
变量(即每个循环上的k += increment
)执行的浮点运算并不精确:您认为将为0.4 + (-0.4)
的实际上
'nearly' '0.4' - 'nearly' '0.4'
;这样,给定您使用的数字范围(以及先前循环中累积的“错误”),您所获得的值(我的系统给出-5.55112e-16
)为零的“合理近似值”。随时要求进一步的澄清和/或解释。
由于增加0.2时会产生舍入误差,因此您的k值永远不会<>零-稍微偏离一点。参见What every computer scientist should know about floating point