爆零求助

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

祝天舒青年湖 @ 2021-11-29 20:50:33

代码如下 各位帮忙看一下

#include<iostream>
using namespace std;
int main(){
    int n,k;
    cin>>n>>k;
    int a[n];
    bool b[n];
    for(int i=0;i<n;i++){
        a[i]=i+1;
        if((i+1)%k==0){
            b[i]=true;
        }
        if((i+1)%k!=0){
            b[i]=false;
        }
    }
    float sum1,sum2;
    sum1=0.0;
    sum2=0.0;
    int num1=1;
    int num2=1;
    for(int i=0;i<n;i++){
        if(b[i]==true){
            sum1+=a[i];
            num1++;
        }
        if(b[i]==false){
            sum2+=a[i];
            num2++;
        }
    }
    cout<<sum1/num1<<" "<<sum2/num2;
    return 0;
}

by ImposterAnYu @ 2021-11-29 20:56:14

@祝天舒青年湖

    int num1=1;
    int num2=1;
   for(int i=0;i<n;i++){
        if(b[i]==true){
            sum1+=a[i];
            num1++;
        }
        if(b[i]==false){
            sum2+=a[i];
            num2++;
        }
    }
    cout<<sum1/num1<<" "<<sum2/num2;

改为:

    int num1=0;
    int num2=0;
   for(int i=0;i<n;i++){
        if(b[i]==true){
            sum1+=a[i];
            num1++;
        }
        if(b[i]==false){
            sum2+=a[i];
            num2++;
        }
    }
    cout<<sum1/max(num1,1)<<" "<<sum2/max(num2,1);

试试?


|