【问题标题】:how many times does i occur in x (unsigned 32 bit int C)我在 x 中出现了多少次(无符号 32 位 int C)
【发布时间】:2014-04-24 03:57:12
【问题描述】:

这对我来说有点令人困惑,但我必须看看 i 在 x 中出现了多少次。 因此,如果有人为 i 输入 3,x 为 4294967295,则应该说 0 次,但如果有人为 i 输入 9,为 x 输入 4294967295,则应该说 3 次。

这就是我所拥有的,但输出显示 0 和 9,所以它不起作用..

int main(int argc, char** argv) {
    unsigned int i;
    scanf("%u", &i);
    unsigned int x;
    scanf("%u", &x);
    int output = 0;
    int t = 0;
    while (t < 10) {
        x /= 10;
        if (i == x) {
            output++;
        }
        t++;
    }
    printf("%d", output);
}

【问题讨论】:

  • 你正在使用t似乎未初始化。
  • output 也未初始化。
  • 为什么要将输入转换为无符号整数?将字符串视为字符串并检查每个字符会更简单。
  • 在你的号码中,x 永远不会是 9,只有 429、42949 和 429496729。检查 x % 10 == i,但 之前除以 10。你的循环条件可以然后只是while (x),您可以删除t
  • 您正在使用的是字符串的属性,而不是数字。我建议你使用字符串函数:)

标签: c int sum unsigned


【解决方案1】:

问题是您将ix整体 进行比较,而不是检查x 的每个数字。

最简单的解决方案可能是将i 读取为字符,确保it's a digit。然后将x 作为字符串读取(并确保它也是所有数字)。然后将字符串x 中的每个字符与i 进行比较。

【讨论】:

  • 感谢您的建议,它确实有效,但效果不佳。 Antoine 的代码解决了这个问题
【解决方案2】:

您应该从x 中提取每个数字并将其与数字i 进行比较。

#include <stdio.h>

int main(void) {
    unsigned int i;
    scanf("%u", &i);
    unsigned int x;
    scanf("%u", &x);
    int output = 0;
    int t = 0;
    while(x > 0) {   
        t = x % 10;  // least significant digit of x
        if(t == x) {
            output++;
        }
        x /= 10;  
    }
    printf("%d", output);
}

【讨论】:

    【解决方案3】:
    int main(int argc, char** argv) {
    
        unsigned int i;
        scanf("%u", &i);
        if(i > 9) {                                 // check it's a single digit
            printf("expecting a single digit\n");
            return 1;                               // to indicate failure
        }
    
        unsigned int x;
        scanf("%u", &x);
    
        int output = 0;      // initialized output, removed t (use x directly instead)
        if(x == 0) {         // special case if x is 0
            if(i == 0) {
                output = 1;
            }
        } else {
    
            while(x > 0) {         // while there is at least a digit
                if(i == (x % 10)) {  // compare to last digit
                    output++;
                }
                x /= 10;            // remove the last digit
            }
    
        }
    
        printf("%d\n", output);    // added \n to be sure it's displayed correctly
        return 0;                  // to indicate success
    
    }
    

    我还建议使用更明确的变量名称,例如 digitnumber 而不是 xi

    【讨论】:

    • 如果输入是 i 0 和 x 0,输出应该是 1,因为 0 和 0 一样,但是输出是 0
    • 确实,我没有想到这种特殊情况。现在已修复。
    • 感谢完美!那个可选块也很好,谢谢!
    • 不客气。检查用户是否真的输入了一个数字是个好主意:我编辑添加了这个。
    • 那里的编码风格相当晦涩...为什么讨厌回车键和缩进?这段代码是在询问错误。
    猜你喜欢
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2013-10-19
    • 2011-11-12
    • 1970-01-01
    • 2011-01-17
    • 2019-10-31
    相关资源
    最近更新 更多