首先,你应该忘记,还有就是goto
声明C.
所有程序包含一个goto
声明,我看到包括一些IBM的源代码必须与goto
陈述许多错误。
goto
声明使程序难以阅读,更难以维护和修改它们。
使用goto
声明是一样的交通violatins。:)
代替这段代码
start:
printf("[c] Converts Celsius -> Fahrenheit\n[f] Converts Fahrenheit -> Celsius\n\n\n");
printf("Enter Choice: ");
scanf("%c",&choice);
if (choice!='c' || choice!='f' || choice!='x') {
printf("Wrong Choice: Try Again!");
goto start;
}
,至少有一个无效的条件if语句
if (choice!='c' || choice!='f' || choice!='x')
代替有效
if (choice!='c' && choice!='f' && choice!='x')
你可以写例如
enum { Celsius = 'c', Fahrenheit = 'f', Exit = 'x' };
char choice;
int valid_input;
do
{
printf("[c] Converts Celsius -> Fahrenheit\n"
"[f] Converts Fahrenheit -> Celsius\n"
"[x] Exit\n\n");
printf("Enter Choice: ");
if (scanf("%c ", &choice) != 1) choice = Exit;
valid_input = choice == Celsius || choice == Fahrenheit || choice == Exit;
if (!valid_input) puts("Wrong Choice: Try Again!\n");
} while (!valid_input);
程序中有许多错误。的Insetad列出他们,我将展示如何 程序可以写
#include <stdio.h>
int main(void)
{
enum { Celsius = 'c', Fahrenheit = 'f', Exit = 'x' };
char choice;
int valid_input;
do
{
printf("[c] Converts Celsius -> Fahrenheit\n"
"[f] Converts Fahrenheit -> Celsius\n"
"[x] Exit\n\n");
printf("Enter Choice: ");
if (scanf("%c ", &choice) != 1) choice = Exit;
valid_input = choice == Celsius || choice == Fahrenheit || choice == Exit;
if (!valid_input) puts("Wrong Choice: Try Again!\n");
} while (!valid_input);
switch(choice)
{
float x, y;
case Celsius: case Fahrenheit:
printf("Input Value: ");
if (scanf("%f", &x) == 1)
{
if (choice == Celsius)
y = 1.8 * x + 32;
else
y = (x - 32) * (5.0f/9.0f);
printf("Result: %.2f\n", y);
}
case Exit:
puts("Bye!");
break;
}
return 0;
}
如果按顺序进入
c 20 x
那么输出将看起来像
[c] Converts Celsius -> Fahrenheit
[f] Converts Fahrenheit -> Celsius
[x] Exit
Enter Choice: c
Input Value: 20
Result: 68.00
Bye!
什么错误?你尝试了什么?你能指望什么? –
在某些情况下使用'goto'被认为是可以的。使用它而不是*循环*不是这些情况之一。你为什么不使用循环? –
一个明显的问题是检查'选择'的'if'语句。条件显然总是如此:它不可能同时与'c','f'和'x'相等,并且测试是,如果它不等于它们中的任何一个,那么做一些事情。如果这真的是你的意图,你可以用'if(1)'代替它。 –