gpt4 book ai didi

c++ - 为什么在for循环中k == 0时,我的程序返回无用值?

转载 作者:行者123 更新时间:2023-12-01 15:13:29 27 4
gpt4 key购买 nike

这是一个简单的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) ...,因为您已将此表达式放在方括号中。因此,它是整数除法,因此将始终具有值为零的值。

试试这个,代替:

    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)

为了安全起见,当您要同时测试 两个条件时,请使用 &&运算符:

for (k = min, l = 0; l < POINTS && k <= max; l++, k += increment) {

最后,您的实际问题是:

There seems to be some problem when k = 0 in the for loop. It is returning a garbage value.



不,这不对!您对 k变量(即每个循环上的 k += increment)执行的浮点操作并不精确:您认为将是 0.4 + (-0.4)的实际上是 'nearly' '0.4' - 'nearly' '0.4';这样,在给定您使用的数字范围(以及先前循环中累积的“错误”)的情况下,您获得的值(我的系统给出 -5.55112e-16)为零的“合理近似值”。

随时要求进一步的澄清和/或解释。

关于c++ - 为什么在for循环中k == 0时,我的程序返回无用值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60271283/

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