我一直在看这个C代码,但不确定它到底在做什么。我不明白如何使用多个if语句来查找语句。
int f(char *s) {
char *p = s;
int c = 1;
while (*p == ’ ’)
++p;
while (*p != ’\0’) {
if ( *p < ’0’ || *p > ’9’ ) {
printf("Error!\n"); return 0;
}
++p; }
for (--p; p >= s; --p) {
if (*p == ’ ’) *p = ’0’;
*p += c;
if (*p > ’9’) {
*p = ’0’; c = 1;
} else
c = 0;
if (c == 0) break;
}
if (c != 0) {
printf("Error!\n");
return 0;
}
return 1; }
最佳答案
// return an integer given a character pointer, a string.
int f(char *s) {
// Set current position to start of string
char *p = s;
// Initialise carry flag to '1'.
int c = 1;
// Move position past leading spaces
while (*p == ’ ’)
++p;
// Check remaining characters are in the set {'0','1',..,'9'}
while (*p != ’\0’) {
// If they are not, return with an error
if ( *p < ’0’ || *p > ’9’ ) {
printf("Error!\n"); return 0;
}
++p; }
// Now counting back from the end of the string
for (--p; p >= s; --p) {
// Turn a space into a '0';
if (*p == ’ ’) *p = ’0’;
// Increment the digit by the value of the carry; one or zero
*p += c;
// This might cause a further carry, capture that
if (*p > ’9’) {
*p = ’0’; c = 1;
} else
c = 0;
// if no carry, break, else keep on with the carry
if (c == 0) break;
}
// If still carrying passed the end of the space, call an error.
if (c != 0) {
printf("Error!\n");
return 0;
}
return 1; }
本质上:如果输入是一个数字字符串,则添加一个;可能需要一个前导空格,如果输入都是“9”,则将使用它。
关于c - 有人可以帮助解释此C算法在做什么吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53312445/