我查看过类似的问题,但没有找到合适的答案。
我正在实现一个 C 代码,它应该读取一个大数(存储在 char*
中),并检查它是否能被 3 整除。
程序运行良好,它打印出有效的答案(您将在函数中看到 printf
正常工作)
我什至尝试定义 1 和 0 并以这种方式返回它,但它仍然不起作用。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ONE 1
#define ZERO 0
int isdiv3(char* s, int sum)
{
/*if string is empty, then check if sum until that point is divisible by 3*/
if(strlen(s) == 0) {
if((sum % 3) == 0) {
printf("yes %d\n", sum);
return ONE;
}
else{
printf("no %d\n", sum);
return ZERO;
}
}
if(strlen(s) == 1)
{
if(!strcmp(s, "3") || !strcmp(s, "6") || !strcmp(s, "9"))
{
return ONE;
}
}
int temp = s[strlen(s) - 1] - '0';
sum += temp;
s[strlen(s) - 1] = '\0';
return sum + isdiv3(s, sum);
}
int main()
{
int x;
char str[200] = "123456";
char *s = malloc(sizeof(char) * 7);
strcpy(s, str);
x = isdiv3(s, 0);
if(x == 1)
printf("%s is divisible by 3\n", str);
else
printf("%s is not divisible by 3\n", str);
printf("x %d\n", x);
//prints x 92
return 0;
}
我的问题是>当return 1
或代码中存在其他任何内容时,它怎么可能打印出一些随机数。
最佳答案
您的 isdiv3
函数包含通向此 return 语句的控制路径
return sum + isdiv3(s, sum);
显然,在一般情况下,该控制路径既不返回 0
也不返回 1
。显然,这正是您所观察到的。
关于C: int 函数返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33224465/