我在 C 中发现了一种奇怪的(对我来说)行为。int如果这是一个基本问题,请注意,但我无法找到为什么以下代码会产生意外结果的答案。
#include <stdio.h>
int main(void)
{
printf("1000 * 0.1 = %d\n", (1000 * 0.1));
printf("1000 * (10/100) = %d\n", (1000 * (10/100)));
printf("(int)1000 * 0.1 = %d\n", (int)(1000 * 0.1));
printf("(int)1000 * (10/100) = %d\n", (int)(1000 * (10/100)));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
两者的结果是-O0相同-O3的:
1000 * 0.1 = -957043896
1000 * (10/100) = 0
(int)1000 * 0.1 = 100
(int)1000 * (10/100) = 0
Run Code Online (Sandbox Code Playgroud)
我预计前两个结果是无意义的(我不知道为什么,但我预计将 double 传递给 int 参数不应该起作用)。然而3和4之间的差异让我感到困惑。我期望(10/100)在编译时计算并呈现与 3 …
c floating-point printf integer-arithmetic conversion-specifier
sscanf()我一直在尝试使用带有前导零的字符串(例如“03”)扫描整数。
然而,它工作正常,但只能到“07”。从“08”开始,字符串将被读取为 0。
您将在下面找到我的代码和输出。感谢您的帮助!
#include <stdio.h>
#include <stdlib.h>
int main() {
char string_six[3] = "06";
char string_seven[3] = "07";
char string_eight[3] = "08";
char string_nine[3] = "09";
int six = -1;
int seven = -1;
int eight = -1;
int nine = -1;
sscanf(string_six, "%i", &six);
sscanf(string_seven, "%i", &seven);
sscanf(string_eight, "%i", &eight);
sscanf(string_nine, "%i", &nine);
printf("Six: %i\n",six);
printf("Seven: %i\n",seven);
printf("Eight: %i\n",eight);
printf("Nine: %i\n",nine);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Six: 6
Seven: 7
Eight: 0
Nine: 0
Run Code Online (Sandbox Code Playgroud) 在 C 中,当我们在or之前使用 ascanf("%s")或时,在输入时,第一个输入的末尾会有一个额外的内容,并且该额外内容将被传递到第二个输入并弄乱输入流。据我所知,我已经在两个不同的系统中使用相同的 gcc 编译器尝试了这些代码。但它每次都做了不同的事情。在第一个系统中,我必须使用 a来丢弃换行符。但在第二个系统中就没有这样的需要了。它自动丢弃换行符。scanf("%c")scanf("%s")scanf("%[^\n]")'\n'scanf("\n")
然后我尝试了三个代码,
代码1:
printf("Enter the name of the student: ");
scanf("%s", name);
printf("Enter the email of the student: ");
scanf("%s", email);
Run Code Online (Sandbox Code Playgroud)
在这里我不必忽略换行符,编译器没有任何问题。
代码2:
printf("Enter the name of the student: ");
scanf("%s", name);
scanf("%*c");
printf("Enter the email of the student: ");
scanf("%s", email);
Run Code Online (Sandbox Code Playgroud)
这里我只是添加了scanf("%*c")来丢弃换行符,这与 具有相同的结果code 1。但是,当我替换scanf("%*c")为scanf("\n")输入时,输入再次混乱,我现在必须提供 3 个输入,因为它没有正确丢弃第一个换行符。
代码3:
char chr, s[100], sen[100];
scanf("%c", &chr);
scanf("\n");
scanf("%s", s);
scanf("\n");
scanf("%[^\n]%*c", …Run Code Online (Sandbox Code Playgroud) #include <stdio.h>
int main()
{
printf("%c code\n", 'C');
printf("%d", "");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
#include <stdio.h>
int main()
{
printf("%d", 3); /* result 3 */
printf("%d", '3'); /* result 51, because 3 is char (from ASCII table) */
printf("%d", ""); /
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我是 C 语言的初学者。我阅读了 Greg Pery 和 Dean Miller 所著的《C 编程绝对初学者指南》第四版。有 %c %d 和 %f 的示例。我开始对它们进行实验,并注意到我无法解释它是如何制作的。所以我用 %d 尝试了这些例子并理解了前两个是如何工作的。对于最后一个,我知道计算机如何读取它,但我不确定所有 0 和 1 是如何组合在一起的。如果您对此有解释,我很乐意回复您)))
int x; 因此变量将有2个字节的内存.现在,如果我输入66并且因为scanf()带有%d,66将存储在2字节内存中,因为该变量被声明为int.
现在在带有%c的printf()中,应该只从一个字节内存中收集数据来显示.
但是%c通过从内存中获取正确的数据66来正确显示B.
为什么%c不只是从一个字节获取数据?