虽然我可以确认我正在输入正确类型的输入到我的C程序中,但我无法让我的条件正确地解释它 . 当我运行以下代码时,程序成功调用 lengthFormula()
,然后打印 "Choose from the following..."
输入提示 .
int main(void)
{
char newCalculation;
do
{
char newCalculation;
lengthFormula();
printf("\nChoose from the following:\n a.) Calculate the length of a multi-bar scene in this project\n b.) Calculate bar length for a NEW project\n c.) Exit\n\n");
scanf(" %c", &newCalculation);
/* printf("%c", newCalculation); */
}while( tolower( newCalculation ) == 'b' );
if( tolower(newCalculation) == 'a' )
{
float barLength;
multiBar(barLength);
}
if( tolower( newCalculation ) == 'c' )
{
exitProgram();
}
return 0;
}
当我输入 a
,而不是再次调用 lengthFormula()
时, main()
返回 0
并且程序终止 . 当我取消注释第二次printf()调用并再次生成/运行时,输入 a
会返回 a
,但它仍会返回 0
/程序终止而不是调用 lengthFormula()
.
在@simplicisveritatis的建议中,我也尝试将我的条件放在主do-while循环中,如下所示,结果相同:
int main(void)
{
char newCalculation;
do
{
char newCalculation;
lengthFormula();
printf("\nChoose from the following:\n a.) Calculate the length of a multi-bar scene in this project\n b.) Calculate bar length for a NEW project\n c.) Exit\n\n");
scanf(" %c", &newCalculation);
/* printf("%c", newCalculation); */
if( tolower(newCalculation) == 'a' )
{
float barLength;
multiBar(barLength);
}
if( tolower( newCalculation ) == 'c' )
{
exitProgram();
}
}while( tolower( newCalculation ) == 'b' );
return 0;
}
如何改变我的条件以便他们认出我的意见?请不要告诉我使用 getchar()
,因为每次我这样做,别人都会告诉我使用 scanf()
,其他人说这很危险 . 我只想了解为什么我的条件不起作用 .
2 回答
您正在循环中重新声明
newCalculation
. 在循环中使用的那个与你所使用的不同 .实际上,在
do
while
循环之外,newCalculation
甚至没有被初始化,所以当你将它传递给tolower()
它可以有任何值时,原则上不可能知道哪一个 .删除循环内的声明,
好吧,让我们从char newCalculation开始吧 . 在您的示例中,一旦在do循环内部,一次在do循环之外,将其声明两次 . 这意味着你有两个,并且do循环中的一个不被while测试识别,这意味着
tolower(newCalculation)
不是你输入的字母,它看到了循环外声明的未初始化的newCalculation中的垃圾 . 删除INTERIOR .此外,在声明它的位置将其初始化为零 .
你表明你有一个习惯,就是不要用
float barLength;
初始化你所声明的内容 . 使float barLength(0);
或类似的东西 .也就是说,你对'a'的测试确实需要正确的条形长度 . 然而,除非通过剪切事故,堆栈在外部newCalculation中留下“b”或“B”,否则循环不会重复 . 你真正想要的是,在这里停止程序'c'...这意味着你不需要函数exitProgram,只需将while测试改为: