为什么我的代码'if statement'在 C 中不起作用?



我写了一个程序,让你输入你的品质,然后程序决定你是否适合当宇航员。但是,它在接受输入时工作,并且不会继续到'if语句'部分。

代码:

#include <stdio.h>
int
main(void)
{
int opt_min;
int opt_max;
int age_min;
int age_max;
int age;
double weight;
char smoking;
printf("Enter the minimum weight an astronaut can be>");
scanf("%d", &opt_min);
printf("Enter the maximum weight an astronaut can be>");
scanf("%d", &opt_max);
printf("Enter the minimum age an astronaut can be>");
scanf("%d", &age_min);
printf("Enter the maximum age an astronaut can be>");
scanf("%d", &age_max);
printf("Enter your weight>");
scanf("%lf", &weight);
printf("Enter your age>");
scanf("%d", &age);
printf("Enter the state of smokingn(if a smoker press 'S' if not press another letter and press return)>");
scanf(" %c", &smoking);
if (weight >= opt_min && weight <= opt_max) {
if (age >= age_min && age <= age_max) {
if (smoking != 'S' || smoking != 's') {
printf("You can be an astronaut!");
}
}
}
else {
printf("Sorry! Your qualities are not enough to be an astronout.");
}
return (0);
}

没有错误,我认为也没有语法错误。它接受输入,然后跳转到返回(0)部分。请帮我一下。

依从者:

Enter the minimum weight an astronaut can be>50
Enter the maximum weight an astronaut can be>150
Enter the minimum age an astronaut can be>20
Enter the maximum age an astronaut can be>50
Enter your weight>55
Enter your age>19
Enter the state of smoking
(if a smoker press 'S' if not press another letter and press return)>j
Program ended with exit code: 0

如果weight在范围内,但agesmoking不是,则您将得到输出。

改变:

if (weight >= opt_min && weight <= opt_max) {
if (age >= age_min && age <= age_max) {
if (smoking != 'S' || smoking != 's') {
printf("You can be an astronaut!");
}
}
}
else {
printf("Sorry! Your qualities are not enough to be an astronout.");
}

为:

if ((weight >= opt_min) && (weight <= opt_max) &&
(age >= age_min) && (age <= age_max) &&
(smoking != 'S') && (smoking != 's')) {
printf("You can be an astronaut!");
}
else {
printf("Sorry! Your qualities are not enough to be an astronout.");
}

在if语句中使用逻辑与运算符是正确的,除了最后一个

if (smoking != 'S' || smoking != 's') {

你必须写

if (smoking != 'S' && smoking != 's') {

至于你的输入

Enter your age>19

则19岁不在可接受的年龄范围内。

else部分属于最外层的if语句获取控件

if (weight >= opt_min && weight <= opt_max) {
//...
}
else {
//...

因此跳过if语句的else部分。

您可以再引入一个变量来存储条件的结果,例如

int valid = (weight >= opt_min && weight <= opt_max) &&
(age >= age_min && age <= age_max) &&
(smoking != 'S' && smoking != 's');
if ( valid )
{
puts("You can be an astronaut!");
}
else 
{
puts("Sorry! Your qualities are not enough to be an astronout.");
}

相关内容

  • 没有找到相关文章

最新更新