我正在研究的问题要求我编写代码,打印从 -1
到 1
inclusive 的每个值,增加一个值0.01
求解数学函数 f(x) = x^2 + 4
(精确到小数点后 4 位)。
示例:
f(-1.00) = 5.0000
f(-0.99) = 4.9801
...
f(1.00) = 5.0000
问题:
我没有得到代码的最后一行:f(1.00) = 5.0000
。我的问题是如何修改我的程序使其出现,你能解释一下为什么它首先不出现吗?
代码:
下面是我的代码。当 x
介于 0
和 1
之间时,它打印出 y
的每个值,f 除外(1.00) = 5.0000
...
double numberForQ4 = -1.00;
double valueOfY = 0;
for ( numberForQ4 = -1.00; numberForQ4 <= 1.00; numberForQ4 += 0.01 ) {
valueOfY = numberForQ4 * numberForQ4 + 4;
printf( "f(%.2f) = %.4f \n", numberForQ4, valueOfY );
}
最佳答案
Why do not get the last line of my output?
float 学具有特殊性,因为 0.01
不能完全表示为 double
,因为它编码为一些 binary 分数。在 OP 的情况下,略高于或低于 0.01 的值以及随后的数学计算只会略微出乎意料的结果。
how do I modify my program
相反,使用整数进行迭代。
// for ( numberForQ4 = -1.00; numberForQ4 <= 1.00; numberForQ4 += 0.01 ) {
for ( int i = -100; i <= 100; i++ ) {
numberForQ4 = i/100.0;
...
提示:iteration最好使用整数对循环进行编码。
can you also explain why it does not appear in the first place, please?
再次尝试您的原始代码并使用足够的精度来查看原因。
printf( ".01 = %.21f\n", 0.01);
for ( numberForQ4 = -1.00; numberForQ4 <= 1.00; numberForQ4 += 0.01 ) {
valueOfY = numberForQ4 * numberForQ4 + 4;
printf( "f(%.21f) = %.21f \n", numberForQ4, valueOfY );
}
关于C:为什么没有得到我输出的最后一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53736421/