初学者 C 程序的意外行为
Unexpected behavior from beginner C program
我正在努力学习更精细级别的计算,并已开始同时学习 Linux 和 C。直到现在一帆风顺。
我 运行 Linux Mint 17 on Kernel 3.16.0-38-generic 并使用 Code::Blocks 13.12 作为我的 IDE.
以下粘贴是我使用数据类型、变量和 printf() 的练习代码,以及我在 vt 中看到的相关输出——我看到的奇怪之处在于我使用浮点数据对小数位进行实验类型,它似乎在小数点后第 5 位和最终第 4 位之后跳过值。
我是否在滥用调用变量的过程,我是否遗漏了代码中的错误,或者这是 CodeBlocks 中的错误?另外——我不确定为什么我的代码片段在预览中完全混在一起,所以我对糟糕的可读性表示歉意
需要编译执行的代码:
/* Prints a message on the screen */
#include <stdio.h>
echar a1 = 'a';
int i1 = 1;
float f1 = 0.123456;
int main()
{
printf("Testing %c la%sof characters using variables \n", a1, "rge string " );
printf("This line has the values %d and %f.\n", i1, f1);
printf("%f can also be displayed as %.5f or %.4f or %.3f or %.2f or %.1f or %.0f \n",
f1, f1, f1, f1, f1, f1, f1);
printf("Which is an integer . . .");
return 0;
}
编译和执行代码的输出
Testing a large string of characters using variables
This line has the values 1 and 0.123456.
0.123456 can also be displayed as 0.12<b>346</b> or 0.12<b>35</b> or 0.123 or 0.12 or 0.1 or 0
Which is an integer . . .
Process returned 0 (0x0) execution time : 0.002 s
Press ENTER to continue.
感谢您提供的任何帮助。我正在学习 C Programming Absolute Beginner - 作者 Greg Perry
如评论中所述,最后一位数字已四舍五入。
如果你有这个:
float f1 = 0.777777;
输出将是这样的:
This line has the values 1 and 0.777777.
0.777777 can also be displayed as 0.77778 or 0.7778 or 0.778 or 0.78 or 0.8 or 1
同样,如果你有这个:
float f1 = 0.999888;
你会得到这个:
This line has the values 1 and 0.999888.
0.999888 can also be displayed as 0.99989 or 0.9999 or 1.000 or 1.00 or 1.0 or 1
我正在努力学习更精细级别的计算,并已开始同时学习 Linux 和 C。直到现在一帆风顺。
我 运行 Linux Mint 17 on Kernel 3.16.0-38-generic 并使用 Code::Blocks 13.12 作为我的 IDE.
以下粘贴是我使用数据类型、变量和 printf() 的练习代码,以及我在 vt 中看到的相关输出——我看到的奇怪之处在于我使用浮点数据对小数位进行实验类型,它似乎在小数点后第 5 位和最终第 4 位之后跳过值。
我是否在滥用调用变量的过程,我是否遗漏了代码中的错误,或者这是 CodeBlocks 中的错误?另外——我不确定为什么我的代码片段在预览中完全混在一起,所以我对糟糕的可读性表示歉意
需要编译执行的代码:
/* Prints a message on the screen */
#include <stdio.h>
echar a1 = 'a';
int i1 = 1;
float f1 = 0.123456;
int main()
{
printf("Testing %c la%sof characters using variables \n", a1, "rge string " );
printf("This line has the values %d and %f.\n", i1, f1);
printf("%f can also be displayed as %.5f or %.4f or %.3f or %.2f or %.1f or %.0f \n",
f1, f1, f1, f1, f1, f1, f1);
printf("Which is an integer . . .");
return 0;
}
编译和执行代码的输出
Testing a large string of characters using variables
This line has the values 1 and 0.123456.
0.123456 can also be displayed as 0.12<b>346</b> or 0.12<b>35</b> or 0.123 or 0.12 or 0.1 or 0
Which is an integer . . .
Process returned 0 (0x0) execution time : 0.002 s
Press ENTER to continue.
感谢您提供的任何帮助。我正在学习 C Programming Absolute Beginner - 作者 Greg Perry
如评论中所述,最后一位数字已四舍五入。
如果你有这个:
float f1 = 0.777777;
输出将是这样的:
This line has the values 1 and 0.777777.
0.777777 can also be displayed as 0.77778 or 0.7778 or 0.778 or 0.78 or 0.8 or 1
同样,如果你有这个:
float f1 = 0.999888;
你会得到这个:
This line has the values 1 and 0.999888.
0.999888 can also be displayed as 0.99989 or 0.9999 or 1.000 or 1.00 or 1.0 or 1