【发布时间】:2021-11-30 16:21:22
【问题描述】:
我正在尝试编写一个程序,该程序将罗马数字作为输入,然后将它们转换为十进制值。用户必须首先声明他们要输入多少个罗马数字(一个或两个)。
我正在使用一个 for 循环,该循环的重复次数与罗马数字的数量一样多。如果只有一个数字,它不应该循环,或者如果有两个,它应该循环两次,因为我们需要一次输入一个字母。
我遇到的问题是 for 循环内的 scanf 语句不断阻止程序循环。一旦我删除了 scanf 并静态分配了值,它就可以正常工作了。然后,在尝试解决问题时,我尝试通过将 scanf 分配给一个新变量(如char snf = scanf("%s", &numeral);)来打印返回的值,并且由于某种原因,它开始工作,正是我希望它工作的原因。我完全不知道它为什么现在工作以及为什么它阻止循环之前循环。谁能给我解释一下这是怎么回事?
// A program to convert Roman Numerals to Decimals system.
#include <stdio.h>
int convert_numerals(char numeral){
switch(numeral){
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default :
printf("\nError! You did not enter a valid numeral\n");
return 0;}}
int main(){
int Decimal_Val = 0; //Initializing the variable with 0 to avoid issues at check.
int Numeral_Count;
printf("How many characters does your Roman numerals have? 1 or 2\n");
scanf("%d",&Numeral_Count);
for (int i = 1; i < 1+Numeral_Count; ++i)
{
char numeral = 'O';
int converted_val;
printf("\n\nEnter numeral %d : ",i);
scanf("%s", &numeral); // The problematic line.
converted_val = convert_numerals(numeral);
if (Decimal_Val != 0)
{
if (Decimal_Val < converted_val)
{
Decimal_Val = converted_val - Decimal_Val;
}else{
Decimal_Val += converted_val;
}
}else{
Decimal_Val = converted_val;
}
}
printf("\nThe Roman numerals you entered are equal to %d in Decimals\n", Decimal_Val);
return 0;
}
【问题讨论】:
-
看起来您正在尝试将字符串读入单个字符...
-
程序仍然无法运行。我之前尝试了很多东西,只有 %s 对我有用,所以我把它放进去。我尝试用 %c 替换它,但问题仍然存在。除非我将 scanf 的返回值分配给其他变量,否则它不会循环两次。