给定 n(n≤10000) 和 k(k≤100),将从 1 到 n 之间的所有正整数可以分为两类:A 类数可以被 k 整除(也就是说是 k 的倍数),而 B 类数不能。请输出这两类数的平均数,精确到小数点后 1 位,用空格隔开。
数据保证两类数的个数都不会是 0。
输入 | 输出 |
---|---|
100 16 |
56.0 50.1 |
相加再除
#include<bits/stdc++.h>
using namespace std;
int n,k,n1c=0,n2c=0;
double n1=0.0,n2=0.0;
int main()
{
cin>>n>>k;
for(int i=1;i<=n;i++)
{
if(i%k==0)
{
n1+=i;
n1c++;
}
else
{
n2+=i;
n2c++;
}
}
cout<<setprecision(1)<<fixed<<n1/n1c<<‘ ‘<<n2/n2c;
return 0;
}
利用等差数列公式
Sn=n(a1+an)/2
#include <bits/stdc++.h>
using namespace std;
double a,b;
int n,k,c;
int main()
{
cin>>n>>k;
c=n/k; //n个数里面有n/k个k的倍数
a=c*(k+c*k)/2; //求c个k的和
b=n*(1+n)/2-a; //n个数的和减c个k的和则是剩下数的和
cout<<setprecision(1)<<fixed<<a/c<<‘ ‘<<b/(n-c);
return 0;
}
原文:https://www.cnblogs.com/codespark/p/14623270.html