gpt4 book ai didi

检查每个数字是否可以被 2 整除

转载 作者:行者123 更新时间:2023-12-02 08:02:43 26 4
gpt4 key购买 nike

我正在编写一个 C 程序,要求用户输入密码并检查数字中的每个数字是否可以被 2 整除。例如,如果他们输入 123452,它会告诉用户这是错误的,因为 1, 2,3,5 不能被 2 整除。如果我输入 642642,它说没问题,但如果我输入 622248,它显示无效数字,这是错误的,因为 622248 中的每个数字都可以被 2 整除。我该如何解决这个问题错误?

#include <stdio.h>
#define N 6

int main(void)
{
int num, digits[N], i, invalid, count = 1, sum = 0;

TOP:
printf("Enter pin code (attempt %d): ", count++);
scanf("%d", &num);

invalid = num;
// stores each digit of the number entered into the the array
for (i = 6; i >= 0; i--) {
digits[i] = num % 10;
num = num / 10;
}
// if the user enters more than 6 digits than it will give you an error.
if (digits[N] > 6) {
printf("Code %d is invalid!\n", invalid);
goto TOP;
}
// loops through the array elements and see if each digit is divisble by 2, if not then print an error.
for (i = 0; i < 6; i++) {
if (digits[i] % 2 != 0) {
printf("Code %d is invalid!\n", invalid);
goto TOP;
}
else {
printf("Congratulation, code %d is valid!\n", invalid);
break;
}
}

return 0;
}

最佳答案

如果您被允许将输入处理为字符串,而不是整数,那么只需要 strspn确定 pin 和 strlen 中数字的有效性判断长度的有效性:

#include <string.h>

size_t len = strlen(str_pin);
if (len <= 6 && strspn(str_pin, "24680") == len)
{
puts("Valid pin");
}
else
{
puts("Invalid pin");
}

关于检查每个数字是否可以被 2 整除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55011319/

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