【问题标题】:Debugging code in C for figuring out length of number?在 C 中调试代码以确定数字的长度?
【发布时间】:2018-06-09 10:38:03
【问题描述】:

所以,我正在编写一个 C 代码,用于计算给定数字的长度。我现在知道正确的方法来解决它。但是,我不明白为什么下面的原始代码是错误的。谁能帮我调试一下?

编辑:我还想知道为什么 while 中的参数应该是 "dgts != 0" 或 "dgts > 0" ?比如,你能解释一下这意味着什么以及为什么有意义吗?

#include <stdio.h>
#include <cs50.h>


int lngth (int dgts);

int main(void){
    int num = get_long_long();
    int length = lngth(num);
    printf("%i",length);
}
int lngth (int dgts){
    int cnt = 0;
    int y = dgts;
    while (dgts !=0 ){
        y = y/10;
         cnt ++;
        printf("%i\n",cnt);
    }
    return cnt;
}

【问题讨论】:

  • 长度取决于编码。 99 可以表示为ninety nine。两者都表达相同的知识,一个长度为 2,另一个为 11。
  • while (dgts !=0 ){ y = y/10;你没有改变dgts所以这里无限循环,应该是while (y){ y /= 10;
  • This article 能帮上大忙。
  • 虽然您的问题的解决方案已经给出,但我仍然建议您学习使用 GDB 等调试器来单步调试您的代码。
  • @Jean-FrançoisFabre 并且有了这个解释,很明显0 也是一个边缘情况(并且没有在解决方案中解决)。

标签: c loops while-loop do-while cs50


【解决方案1】:

正如 Jean-François Fabre 在 cmets 中提到的,您在 int lngth (int dgts) 函数中创建了一个无限循环:

    while (dgts !=0 ){
        y = y/10;
        ...
    }

因为条件 dgts != 0 依赖于 dgts 而不是 y,而 y 是在 y = y/10 处发生变化的那个,所以循环永远不会完成。

【讨论】:

    【解决方案2】:

    代码有2个问题:

    1. while (dgts !=0 ){ y = y/10; cnt ++; }dgts 的无限循环永远不会改变,所以一旦代码进入循环它就会卡在那里。 @Jean-François Fabre

    2. dgts == 0 时的安排有问题,因为这通常是一个数字而不是无数字。 do 循环是一个简单的解决方案。

    修复代码:

    int lngth(int dgts) {
      int cnt = 0;
      do {
        cnt++;
        printf("%i\n", cnt);
        dgts /= 10; 
      } while (dgts);  // while dgts is non-zero
      return cnt;
    }
    

    给定数字的长度正在研究小数位数的概念。如果长度包括负数的'-',则只需进行少量更改。

      // int cnt = 0;
      int cnt = dgts < 0;
    

    【讨论】:

      【解决方案3】:

      while循环的条件有错别字

      while (dgts !=0 ){
             ^^^^^^^^
      

      我认为你的意思是

      while (y !=0 ){
             ^^^^^
      

      但无论如何该函数都是错误的,因为它的参数可以等于0,而0 是一个包含一位数字的有效数字。

      另外,将返回类型定义为int 也没有意义,因为数字的长度不能为负值。

      函数看起来像

      unsigned int lngth ( int dgts )
      {
          const int Base = 10;
      
          unsigned int cnt = 0;
      
          do
          {
              ++cnt;
          } while ( dgts /= Base );
      
      
          return cnt;
      }
      

      你应该在 main 中写

      unsigned int length = lngth(num);
      printf("%u\n", length );
      

      还要考虑到函数get_long_long 似乎返回long long int 类型的整数。

      如果是这样,那么你应该写

      long long int num = get_long_long();
      

      在这种情况下,应该声明函数

      unsigned int lngth ( long long int dgts );
      

      请注意,没有理由声明像 dgtslngth 这样的标识符。使用完整的单词。例如

      unsigned int length ( long long int number );
                   ^^^^^^                 ^^^^^^
      

      或者只是

      unsigned int length ( long long int n );
                   ^^^^^^                ^^^
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        相关资源
        最近更新 更多