【问题标题】:Can someone help explain what this C algorithm is doing?有人可以帮助解释这个 C 算法在做什么吗?
【发布时间】:2019-04-18 03:24:37
【问题描述】:

我一直在查看这段 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; }

【问题讨论】:

  • 那不是有效的 C 代码。 wandbox.org/permlink/2flW7TlwG4y6Oynz
  • 总体思路是什么?这个密码是从天上掉到你身上的吗?你得到它的地方没有解释一下吗?
  • 不如描述一下代码对我们做了什么。如果你弄错了,人们可能会给予指点。与人们不费吹灰之力地告诉你发生了什么相比,你会学到更多的使用方法。而且,顺便说一句,代码的作用非常简单。
  • '替换所有
  • 如果字符串包含一个整数(带有前导空格),则将该整数加一。成功返回 1,失败返回 0。

标签: c string algorithm


【解决方案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',就会使用它。

【讨论】:

  • 整个for (--p; p &gt;= s; --p) 循环减少到*(--p) += 1; c = 0; 顺便说一句。
  • @HenriMenke 谢谢。似乎已经设法向后阅读临界线;现在有点道理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 2018-04-26
  • 2018-07-23
  • 2020-01-31
  • 2021-04-07
  • 2011-12-13
相关资源
最近更新 更多