c - 忽略返回值(C 编程)
问题描述
几天前我刚开始学习 C 编程,我正在尝试从 Kattis (open.kattis.com) 网站上解决一些问题。我一路上遇到了这个问题,我真的不明白它的意思。
//two stones
#include <stdio.h>
int main()
{
int n,x=2;
printf("The number of stones placed on the ground is ");
scanf("%d",&n);
if (n%x != 0)
{
printf("The winner of the game is Alice! \n");
}
else
{
printf("The winner of the game is Bob! \n");
}
return 0;
}
这出现了>>
警告:忽略 scanf 的返回值,用关于 scanf("%d",&n) 的属性 warn_unused_result [-Wunused-result] 声明;
谁能解释这有什么问题以及如何解决这个问题?谢谢。
解决方案
scanf
有一个指示成功的返回值:
C标准;§7.19.6.4.3:
如果在任何转换之前发生输入失败,scanf 函数将返回宏 EOF 的值。否则,scanf 函数会返回分配的输入项的数量,如果出现早期匹配失败,该数量可能会少于提供的数量,甚至为零。
如果您的调用中有一个具有一个格式说明符的格式字符串,那么您可以通过将其返回值与 1 进行比较scanf
来检查是否scanf
成功从 接收该类型的输入。stdin
你的编译器警告你这不是特别是因为scanf
返回一个值,而是因为检查scanf
. printf
例如,符合标准的.
推荐阅读
- python - on_click(x, y, button, pressed) 不起作用,分配前引用了局部变量“pressed”
- kubernetes - 如何解决谷歌云上的“所有主机都被其他资源占用”?
- xcode - 无法在 Big Sur 上构建 Racket 7.9
- javascript - 悬停事件上的谷歌图表自定义图例
- c# - Keyset(Seek) 分页和 MongoDb 驱动程序 C#
- docker - 是否可以从 Redhat linux docker 基础映像之一中删除 unwating sqlite 包
- c - 编译 Visual Studio dll 并将其与 cygwin 一起使用
- python - Django 'Query' 对象没有属性 'contains_column_references'
- r - 在 R 函数中创建可重用对象的推荐方法
- php - Yii2 PHP Try Catch未在视图index.php中触发