C:为什么没有得到我输出的最后一行?

标签 c

我正在研究的问题要求我编写代码,打印从 -11 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 介于 01 之间时,它打印出 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/

相关文章:

java - 将函数指针转换为 long

c - 打印链表中的值对

c - 如何在 c 中立即发出信号警报

c - 旧的 EBP 和返回地址在哪里?

c - if 语句忽略零?

c++ - 应用程序认为它在我的主文件夹中 OSX

c - MongoDB 在 C 中使用 $or 检索记录

c - 为什么我的 read() 系统调用返回 -1?

在 QT Creator 中捕获单元测试 - main 的多个定义

php - 在编译期间检测 PHP 是否正在使用给定的扩展名进行编译