输出与输入不匹配(C语言)
The output does not match with the input (C language)
我正在制作一个简单的 C 程序,它会询问您的年龄和性别。如果您的性别不是 M 或 F,程序将要求输入不同的信息。如果您的年龄小于零,程序将需要另一个输入。这是我的代码:
#include<stdio.h>
int main(){
int a;
char g;
entry:
printf("%s","AGE : ");
scanf("%d", &a);
getchar();
insert:
printf("%s","GENDER :");
scanf("%s", &g);
getchar();
while (a < 0){
goto entry;
}
switch(g){
case 'M':{
printf("I am a %d yr old male", a);break;
}
case 'F':{
printf("I am a %d yr old female", a);break;
}
default:{
goto insert; break;
}
}
return 0;
}
这是程序的一个例子运行
年龄:21
性别:男
我是0岁男
虽然我在代码中发现了一个奇怪的地方(见大注释),但它的输出符合您的预期,因此您可以使用这样的方法:
#include<stdio.h>
#include<stdbool.h>
int main(){
int age, a;
char g;
bool validInput;
do {
validInput = true;
printf("%s","AGE : ");
scanf("%d", &age);
/*
* If you use directly the 'a' var, somehow it will not print
* input age. That's why I had to use a = age assignment.
* This is weird, if someone knows why this happens let me
* know please.
*/
a = age;
if(a < 0) {
validInput = false;
}
printf("%s","GENDER : ");
scanf("%c", &g);
getchar();
if(g != 'M' && g != 'F') {
validInput &= false;
}
} while(!validInput);
switch(g){
case 'M':
printf("I am a %d yr old male\n", a); break;
case 'F':
printf("I am a %d yr old female\n", a); break;
default:
printf("Oops! Something went wrong...\n");
}
return 0;
}
我正在制作一个简单的 C 程序,它会询问您的年龄和性别。如果您的性别不是 M 或 F,程序将要求输入不同的信息。如果您的年龄小于零,程序将需要另一个输入。这是我的代码:
#include<stdio.h>
int main(){
int a;
char g;
entry:
printf("%s","AGE : ");
scanf("%d", &a);
getchar();
insert:
printf("%s","GENDER :");
scanf("%s", &g);
getchar();
while (a < 0){
goto entry;
}
switch(g){
case 'M':{
printf("I am a %d yr old male", a);break;
}
case 'F':{
printf("I am a %d yr old female", a);break;
}
default:{
goto insert; break;
}
}
return 0;
}
这是程序的一个例子运行
年龄:21
性别:男
我是0岁男
虽然我在代码中发现了一个奇怪的地方(见大注释),但它的输出符合您的预期,因此您可以使用这样的方法:
#include<stdio.h>
#include<stdbool.h>
int main(){
int age, a;
char g;
bool validInput;
do {
validInput = true;
printf("%s","AGE : ");
scanf("%d", &age);
/*
* If you use directly the 'a' var, somehow it will not print
* input age. That's why I had to use a = age assignment.
* This is weird, if someone knows why this happens let me
* know please.
*/
a = age;
if(a < 0) {
validInput = false;
}
printf("%s","GENDER : ");
scanf("%c", &g);
getchar();
if(g != 'M' && g != 'F') {
validInput &= false;
}
} while(!validInput);
switch(g){
case 'M':
printf("I am a %d yr old male\n", a); break;
case 'F':
printf("I am a %d yr old female\n", a); break;
default:
printf("Oops! Something went wrong...\n");
}
return 0;
}