gpt4 book ai didi

c - 将文本放入 scanf 会使代码输出随机数?

转载 作者:行者123 更新时间:2023-12-01 21:52:57 25 4
gpt4 key购买 nike

我正在计算机课上学习 C,今天我们学习了 scanf。这是用于引入 scanf 的代码行:

#include <stdio.h>
void main()
{
float x,y;
scanf("%f %f",&x,&y);
printf("%2f\n",x+y);
}

这很好用,如果你输入两个数字,它会打印出总和。我认为它可能像 pythons 输入函数一样工作,所以我修改了上面的代码以在 scanf 中包含一些文本,如下所示:

#include <stdio.h>
void main()
{
float x,y;

scanf("insert no in format x y %f %f",&x,&y);

printf("%2f\n",x+y);
}

我得到的输出不是 10,而是一些随机数。我说随机是因为我尝试多次运行代码,每次我收到不同的输出。

这与内存分配有关吗? scanf 可以不是字符串吗?

最佳答案

scanf 用于读取输入,而不是打印输出。如果您将文本放在那里,它会尝试匹配该文本。如果它无法匹配该文本(您必须输入确切的文本),该函数将失败,并且如果您稍后尝试使用这些值,则会出现未定义的行为。参见 here (强调我的):

Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.

您可以通过检查返回值来确保它成功读取值:

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

所以在这种情况下,你的返回值应该是2

如果你想打印那个文本,你可以使用 printf 代替:

printf("insert no in format x y");
if (scanf("%f %f",&x,&y) != 2){
printf("Error reading in the parameters!");
return -1;
};

关于c - 将文本放入 scanf 会使代码输出随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58917640/

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