c++0分求助

P5719 【深基4.例3】分类平均

Leskoreyoshi @ 2023-01-10 11:19:39

#include<bits/stdc++.h>
using namespace std;

vector<int>a,b;
int main()
{
int n,k,sum1,sum2;
    cin>>n>>k;
    for(int i=1;i<=n;i++)
{
if(i%k==0)
{a.push_back(i);
sum1+=i;}
else
{b.push_back(i);
sum2+=i;}
}
   cout<<fixed<<setprecision(1)<<(double)sum1/a.size()<<" "<<(double)sum2/b.size();
return 0;
}

by wssb1919810 @ 2023-01-10 12:20:55

#include<bits\stdc++.h>
using namespace std;
int n,k,sum;//没啥解释的
int main(){
    cin>>n>>k;//输入
    for (int i=k;i<=n;i+=k) sum+=i;//循环做整除k整除i
    printf ("%.1f ", double (sum)/(n/k));//一共有n/k个,用sum除去数量得到平均数 
    sum=(1+n)*n/2-sum;//(1+2+3+4+...+n)-sum(此时sum为k整除i的所有i之和,做完运算就是所有k不整除i的i之和)
    printf (“%.1f\n”, double (sum)/(n-n/k));//剩余n-n/k个,sum除一下输出来
    return 0;
}//防复制已准备

by Leskoreyoshi @ 2023-01-10 12:59:25

@wssb1919810 我这个stl用的有啥问题吗


by wssb1919810 @ 2023-01-10 13:01:02

@Leskoreyoshi 我现在在找,找到了私信你


by wssb1919810 @ 2023-01-10 13:04:06

试了下样例,输出来70w多和2w多 显然不对


by wssb1919810 @ 2023-01-10 13:13:35

把局部变量换成全局变量或者赋初值为0试试


by wssb1919810 @ 2023-01-10 13:16:38

没问题,就是初值乱的,得设成0

#include<bits/stdc++.h>
using namespace std;
vector<int>a,b;
int n,k,sum1,sum2;
int main(){
    cin>>n>>k;
    for(int i=1;i<=n;i++){
        if(i%k==0){
            a.push_back(i);
            sum1+=i;
        }
        else{
            b.push_back(i);
            sum2+=i;
        }
    }
   cout<<fixed<<setprecision(1)<<(double)sum1/a.size()<<" "<<(double)sum2/b.size();
    return 0;
}

by Leskoreyoshi @ 2023-01-10 13:21:18

@wssb1919810 感谢感谢!!


|