我写了这段代码: 它不是印刷品。 我意识到在scanf的调用中有一个'\\ n'。 当我删除它时,我得到了预期的输出。 当scanf格式字符串包含'\\ n'时,为什么不给出输出? 是什么原因? ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
对于一项作业,我被要求创建一个小程序,该程序要求用户输入以确定他们希望操作的转换器。 我的问题是,在输入想要使用的转换器(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) {
用这种方式格式化花括号实际上将消除这种类型的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.