记录一道C语言题目
程序员文章站
2022-05-12 14:01:29
...
记录一道C语言题目
很简单的一个题。磨磨脑子,最近有点手生。
题目:
统计各位数字之和是5的数
本题要求实现两个函数:一个函数判断给定正整数的各位数字之和是否等于5;另一个函数统计给定区间内有多少个满足上述要求的整数,并计算这些整数的和。
我讲得可能不算很清楚,具体请查看题目链接
代码实现:
#include<stdio.h>
#include<math.h>
#define N 5
#define M 10
int cal(int n){
int m = 0;
for (;;n/=10) {
if (n)m++;
else break;
}
return m;
}
int judge(int i,int con) {
int num = cal(i), sum = 0, q = i;
for (int j = num; j > 0; j--) {
//calculate the sum of decimal digits of this number
int tem= q / pow(M, j - 1);
sum += tem;
q -= tem*pow(M, j - 1);
}
if (sum == con)return 1;
else return 0;
}
void sta(int a, int b, int n,int count) {
int add = 0;
for (int i = a; i <= b; i++) {
if (judge(i,N)) {
count++; add += i;
}
}
printf("count is %d,sum is %d\n", count,add);
}
int main() {
int a, b, n, count = 0;
//Calculate the sum of all numbers which could meet the condition
scanf("%d,%d", &a, &b);
sta(a, b, N, count);
//Judge whether the number you inputed could meet the condition
scanf("%d", &n);
if (n >= a && n <= b){
if (judge(n, N))printf("%d is counted.\n", n);}
else printf("error input!\n");
return 0;
}
核心函数是judge子函数:
int judge(int i,int con) {
int num = cal(i), sum = 0, q = i;
for (int j = num; j > 0; j--) {
//calculate the sum of decimal digits of this number
int tem= q / pow(M, j - 1);
sum += tem;
q -= tem*pow(M, j - 1);
}
if (sum == con)return 1;
else return 0;
}
运行效果是这样的(举例):
或者:
或者:欢迎讨论。