与解答基本一致,为何不对求调

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

Fwdx_Su @ 2024-05-06 16:57:47

#include <iostream> 
#include<cstdio>
using namespace std ;
int main()
{
    int n , k = 0 ;
    cin >> n ;
    cin >> k ;
    double aveA , aveB , sumA , sumB  ;
    int numA ,numB = 0 ;
    for(int i = 1 ; i <= n; i++)
    {
        if( i % k == 0 )
        {
            sumA += i ;
            numA ++ ;
        }
        else
        {
            sumB += i ;
            numB ++ ;
        }
    }
    aveA =sumA / numA ;
    aveB = sumB / numB ;
    printf("%.1lf %.1lf",aveA,aveB) ;
    return 0;
}

by ___Furina___ @ 2024-05-06 17:02:00

@Fwdx_Su 你没有给numA赋初值0


by penguin_is_cool @ 2024-05-06 17:09:06

@Fwdx_Su numA 如果没有赋初始值,每次运行答案就会不一样


by yjy_echo @ 2024-05-06 17:30:46

@Fwdx_Su 不给n赋值的话,放在main函数里面会自动赋随机值,所以要改为 int n = 0 , k = 0;


by Leaf59 @ 2024-07-27 12:17:33

简单一点

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

|