【发布时间】:2011-02-15 05:57:15
【问题描述】:
以下代码编译良好,但不允许用户选择是否再次运行程序。给用户答案后,程序自动终止。我将主代码放在一个“do while”循环中,如果我愿意,我也可以转换不止一次。我尝试在命令行(Mac 和 Ubuntu 机器)和 XCode 中运行该程序,结果完全相同。任何帮助将不胜感激。
- C 初学者
附:在运行 Snow Leopard 的 MacBookPro 上编译。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char anotherIteration = 'Y';
do
{
const float Centimeter = 2.54f;
float inches = 0.0f;
float result = 0.0f;
// user prompt
printf("\nEnter inches: ");
scanf("%f", &inches);
if (inches < 0) {
printf("\nTry again. Enter a positive number.\n");
break;
} else {
// calculate result
result = inches * Centimeter;
}
printf("%0.2f inches is %0.2f centimeters.\n", inches, result);
// flush input
fflush(stdin);
// user prompt
printf("\nWould you like to run the program again? (Y/N): ");
scanf("%c", &anotherIteration);
if ((anotherIteration != 'Y') || (anotherIteration != 'N'))
{
printf("\nEnter a Y or a N.");
break;
}
} while(toupper(anotherIteration == 'Y'));
printf("Program terminated.\n");
return 0;
}
【问题讨论】:
-
下次请格式化您的代码。
标签: c