實(shí)驗(yàn)2-4-1 統(tǒng)計(jì)各位數(shù)字之和是5的數(shù) (20 分)
1. 題目摘自
https://pintia.cn/problem-sets/13/problems/411
2. 題目內(nèi)容
本題要求實(shí)現(xiàn)兩個(gè)函數(shù):一個(gè)函數(shù)判斷給定正整數(shù)的各位數(shù)字之和是否等于5;另一個(gè)函數(shù)統(tǒng)計(jì)給定區(qū)間內(nèi)有多少個(gè)滿足上述要求的整數(shù),并計(jì)算這些整數(shù)的和探入。
函數(shù)接口定義:
int is( int number );
void count_sum( int a, int b );
函數(shù)is判斷number的各位數(shù)字之和是否等于5勿侯,是則返回1,否則返回0屏镊。
函數(shù)count_sum利用函數(shù)is統(tǒng)計(jì)給定區(qū)間[a, b]內(nèi)有多少個(gè)滿足上述要求(即令is返回1)的整數(shù)虱颗,并計(jì)算這些整數(shù)的和罗丰。最后按照格式count = 滿足條件的整數(shù)個(gè)數(shù), sum = 這些整數(shù)的和
進(jìn)行輸出。題目保證0<a≤b≤10000。
輸入樣例:
104 999
輸出樣例:
104 is counted.
count = 15, sum = 3720
3. 源碼參考
#include <iostream>
#include <iomanip>
using namespace std;
int is(int number);
void count_sum(int a, int b);
int main()
{
int a, b;
cin >> a >> b;
if (is(a))
{
cout << a << " is counted." << endl;
}
if (is(b))
{
cout << b << " is counted." << endl;
}
count_sum(a, b);
return 0;
}
int is (int number)
{
int n = number;
int s = 0;
do
{
s += n % 10;
n /= 10;
} while (n != 0);
if (s == 5)
{
return 1;
}
return 0;
}
void count_sum(int a, int b)
{
int count = 0;
int sum = 0;
for(int i = a; i <= b; i++)
{
if(is(i))
{
count++;
sum += i;
}
}
cout << "count = " << count << ", sum = " << sum <<endl;
return;
}