gpt4 book ai didi

c - 即使输入正确,if 语句也始终为真?

转载 作者:太空宇宙 更新时间:2023-11-04 06:47:24 25 4
gpt4 key购买 nike

我正在对项目中输入的月份进行一些检查。我扫描 2 个字符。假设我成功地将“10”作为输入。然后通过 if 语句,我询问编译器所采用的输入是否大于 12 或小于 01 ,但在任何情况下,if 语句始终为真。

#define MAX_DAY 2
#define MAX_MONTH 2
#define MAX_YEAR 4

#include <stdio.h>
#include <stdlib.h>

typedef struct {
char day[MAX_DAY];
char month[MAX_MONTH];
char year[MAX_YEAR];
} date; //struct data

typedef struct {
date date_of_flight;
} flight; //struct volo

int CheckMonth (flight list1);

int main() {

flight list;

int correct = 0;

while (correct != 1) {
printf("Month of departure: ");
scanf("%2s", list.date_of_flight.month);
correct = CheckMonth(list);
}

return 0;
}

int CheckMonth (flight list1) {

int correct = 0;

if ((list1.date_of_flight.month > 12) || (list1.date_of_flight.month < 01)) {
printf("Wrong input. The right input should be between 01 (January) and 12 (December).\n");
}
else
{
correct = 1;
}
return correct;
}

如果您问自己为什么我使用 char month[] 而不是简单的 int,那是因为如果我通过 int 扫描“05”,scanf 只会读取 5。

最佳答案

您需要在函数中比较字符串。

if ((list1.date_of_flight.month > 12) || (list1.date_of_flight.month < 01))  {
printf("Wrong input. The right input should be between 01 (January) and 12 (December).\n");

实际上应该是:

if ((strcmp(list1.date_of_flight.month, "12") > 0 ) || (strcmp(list1.date_of_flight.month, "01") < 0))  {
printf("Wrong input. The right input should be between 01 (January) and 12 (December).\n");
}

strcmp()<string.h> 中的函数.如果两个字符串相等,则返回 0。

如果第一个字符串中的第一个不同字符出现在第二个字符串中的不同字符之后,则根据 ASCII 值返回一个负数。

否则,它返回一个正数。

关于c - 即使输入正确,if 语句也始终为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56198636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com