[英]How do I sum the digits of a number and then check if it exists in other number
如何创建一个函数,该函数将采用两个整数num1
、 num2
并返回一个整数,并且该函数将检查数字num2
的数值是否在数字num1
的数字中。 例如num1 = 51749
, num2 = 566
: num1
有17
, 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
为零或不为零,则将0
或1
分配给sum
。
另请注意,您的函数不会测试num2
中的数字总和是否存在于num1
中。 您必须使用不同的方法:
sum2
: num2
中的数字总和num1
中(因为sum2
有 1 位或 2 位数字)。这是修改后的版本:
#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.