c - 要求输入数字直到输入零的算法
问题描述
我正在尝试在 C 中创建一个算法,要求您输入任何数字,并在您输入数字 0 时停止询问。我应该使用 while 循环来完成,但它不起作用,我尝试了一切我学过。这是我的代码不起作用:
#include<stdio.h>
int main()
{
int number;
while(number != 0)
{
printf("Introduce a number: ");
scanf("%i",&number);
}
return 0;
}
解决方案
希望现在把我的两分钱带到聚会上还为时不晚。
其他人建议的解决方案绝对是可能的并且可行的解决方案,但是,我认为它可以以稍微整洁的方式完成。对于这样的情况,do while
存在语句:
#include <stdio.h>
int main() {
int number; // Doesn't need to be initialized in this case
do {
printf("Introduce a number: ");
if (scanf("%i", &number) != 1) { // If the value couldn't be read, end the loop
number = 0;
}
} while (number != 0);
return 0;
}
我认为这个解决方案更好的原因只是它没有给代码带来任何其他魔法常量,因此它应该更好地阅读。
例如,如果有人看到int number = 42;
,他会问 - 为什么是 42?为什么初始值是 42?这个值是否在某处使用?答案是:不,它不是,因此没有必要在那里拥有它。
推荐阅读
- javascript - 即使有数据也会显示错误消息,有时甚至没有数据
- ios - SCNText 中缺少字符(iOS 14)
- overpass-api - 提取一个国家的所有多边形状态
- sql - 使用 STRING_AGG 函数时子查询返回多行
- jupyter-notebook - Jupyter 笔记本服务器:限制对选定 IP 的访问
- python - 如何从 django 管理员下载最新上传的文件?
- python - 如何从 Python 中的 WTForm 字段中提取值?
- jenkins - 使用 Jenkins 签出项目时获取远程 repo 'origin' 时出错
- python - 如何在 tkinter 窗口中显示控制台窗口输出结果?
- spring - Spring Cloud Resilience4j Circuitbreaker 未调用回退