c - 简单的 IF 语句 scanf
问题描述
对于一项任务,我被要求创建一个小程序,该程序要求用户输入确定他们希望操作的转换器。我的问题是为什么程序不要求用户输入,在他们输入他们希望使用的转换器(1 或 2)之后。它没有调用scanf,而是一次运行整个语句。
#include <stdio.h>
int main()
{
float cm;
float inches;
int operation;
printf("Hello and welcome to the Inches to Centimetres converter. \n");
printf("Choose from the options below by entering the corresponding number:\n");
printf("Inches to CM converter (1)\n");
printf("CM to Inches converter (2)\n");
scanf("&d", &operation);
if (operation == 1)
{
printf("Please enter the amount of Inches you wish to convert : \n");
scanf("%f", &inches);
cm = inches * 2.54;
if (inches <= 0)
{
printf("Invalid number");
}
else
printf("%f inches is equal to %f centimetres.", inches, cm);
}
else if (operation == 2);
{
printf("Please enter the amount of Centimetres you wish to convert : ");
scanf("%f", &cm);
inches = cm / 2.54;
if (cm <= 0)
{
printf("Invalid number");
}
else
printf("%f centimetres is equal to %f inches.", cm, inches);
}
}
输出
解决方案
这里有两个问题。第一的:
scanf("&d", &operation);
有一个错字,“&d”应该是“%d”,这就是为什么你会立即收到两次提示。你要:
scanf("%d", &operation);
其次是这样的:
}
else if (operation == 2);
{
;
立即结束该块else
。因此大括号中的块将始终运行。摆脱;
}
else if (operation == 2)
{
更好的是:
} else if (operation == 2) {
以这种方式格式化大括号实际上可以消除这种类型的错误。
推荐阅读
- java - 如何在可折叠表格中一次只显示一行,切换
- php - 树枝循环不是循环一次而是多次
- c++ - 试图用命令行参数做一个简单的问题,指针让我难过
- android-studio - 新的“Empty Acitivity”模板应用程序上未显示材料设计
- permissions - 给予管理员同意后如何修复“AADSTS90094:此应用程序需要对另一个应用程序的应用程序权限”错误
- windows - 如何在 Windows 启动时运行 git bash 脚本
- cypress - 通过嵌套的 ng-reflect-model 值获取元素
- java - Jackson 将 POJO 序列化为 JS 对象
- java - Java7 WeakHashMap isEmpty() 似乎是错误的
- c++ - 如何在 C++ 中创建定时器 无法计算出 CALLBACK 的定时器 ID 值