繁体   English   中英

如何对一个数字的数字求和,然后检查它是否存在于其他数字中

[英]How do I sum the digits of a number and then check if it exists in other number

如何创建一个函数,该函数将采用两个整数num1num2并返回一个整数,并且该函数将检查数字num2的数值是否在数字num1的数字中。 例如num1 = 51749 , num2 = 566 : num117 , num2和是17

int func(int num1, int num2)这是没有数组的函数的开始。 我开始了这个,但由于某种原因它不起作用,你能解释一下是什么问题吗?

#include <stdio.h>
#include <stdlib.h>

int func(int num1, int num2) {
    int sum = 0, sum2 = 0, ad = 0;
    int digit;

    while (num1 > 0) {
         digit = num1 % 10;
         sum = sum + digit;
         num1 = num1 / 10;
    }
    while (num2 > 0) {
         digit = num2 % 10;
         sum2 = sum2 + digit;
         num2 = num2 / 10;
    }
    while (ad < 10) {
        if (sum =! num2)
            printf("The number is correct");
        ad++;
    }
    printf("Different");
}

int main() {
    int a, b;
    printf("Type the first number ");
    scanf("%d", &a);
    printf("Type the second number ");
    scanf("%d", &b);
    if (func(a, b) == 1)
        printf("Yes");
    if (func(a, b) == 0)
        printf("No");

    return 0;
}

if (sum =! num2)中有一个错字:您可能是这个意思:

if (sum != num2)

如果您想知道为什么伪造的表达式会编译, sum =! num2 sum =! num2被解析为sum = !num2如果num2为零或不为零,则将01分配给sum

另请注意,您的函数不会测试num2中的数字总和是否存在于num1中。 您必须使用不同的方法:

  • 计算sum2 : num2中的数字总和
  • 测试此数字是否以 1 位或 2 位数字的形式出现在num1中(因为sum2有 1 位或 2 位数字)。
  • 您可能需要制作 (0, 0) 的特殊情况。

这是修改后的版本:

#include <stdio.h>

int func(int num1, int num2) {
    int sum2 = 0;

    while (num2 > 0) {
         sum2 += num2 % 10;
         num2 /= 10;
    }
    if (sum2 == 0 && num1 == 0)
        return 1;   // special case for (0, 0)

    while (num1 > 0) {
         if (num1 % 10 == sum2)
             return 1;   // sum2 has 1 digit and is present
         if (num1 % 100 == sum2)
             return 1;   // sum2 has 2 digits and is present
         num1 /= 10;
    }
    return 0;  // sum2 is not present
}

int main() {
    int a = 0, b = 0;
    printf("Type the first number: ");
    scanf("%d", &a);
    printf("Type the second number: ");
    scanf("%d", &b);
    if (func(a, b)) {
        printf("Yes\nsum of digits in %d is present in %d\n", b, a);
    } else {
        printf("No\nsum of digits in %d is not present in %d\n", b, a);
    }
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM