C语言,全WA,救救蒟蒻

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

bright_mountain @ 2024-12-06 17:48:09

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,k;
    scanf("%d %d",&n,&k);
    int *ass1,*ass2;
    ass1=(int*)malloc(n*sizeof(int*));
    if(ass1==NULL) return 1;
    ass2=(int*)malloc(n*sizeof(int*));
    if(ass2==NULL) return 1;
    int j=0,h=0;
    for(int i=1;i<=n;i++){
        if(i%k==0){
            ass1[j]=i;
            j++;
        }else{
            ass2[h]=i;
            h++;
        }
    }
    int sum1;
    int sum2;
    for(int t=0;t<j;t++){
        sum1+=ass1[t];
    }
    for(int t=0;t<h;t++){
        sum2+=ass2[t];
    }
    float aver1=sum1/j;
    float aver2=(float)sum2/h;
    printf("%.1f %.1f",aver1,aver2);
    free(ass1);
    free(ass2);
    return 0;
}

by mopeicong @ 2024-12-06 18:16:09

这道题逻辑其实很清晰
几个变量就够了,不明白你为什么搞那么复杂

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

int main(){
    int n,k;
    int ansa=0,ansb=0;
    int suma=0,sumb=0;
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++){
        if(i%k==0) suma += i,ansa++;
        else sumb += i,ansb++;
    }
    double resa = suma*1.0/ansa;
    double resb = sumb*1.0/ansb;
    printf("%.1lf %.1lf",resa,resb);
    return 0;
}

by pies_0x @ 2024-12-06 18:27:10

@GavinCQTD 指针仙人


by pies_0x @ 2024-12-06 18:36:41

@bright_mountain

指针仙人坠了

首先, 你的第 30 行应该先将 sum1 转为 float 类型(你用的) 再计算

其次, 你这我加一句调试就炸:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,k;
    scanf("%d %d",&n,&k);
    int *ass1,*ass2;
    ass1=(int*)malloc(n*sizeof(int*));
    if(ass1==NULL) return 1;
    ass2=(int*)malloc(n*sizeof(int*));
    if(ass2==NULL) return 1;
    int j=0,h=0;
    for(int i=1;i<=n;i++){
        if(i%k==0){
            ass1[j]=i;
            j++;
        }else{
            ass2[h]=i;
            fprintf(stderr,"%d ",ass2[h]); // 加这一句就炸了
            h++;
        }
    }
    int sum1;
    int sum2;
    for(int t=0;t<j;t++){
        sum1+=ass1[t];
    }
    for(int t=0;t<h;t++){
        sum2+=ass2[t];
    }
    float aver1=(float)sum1/j;
    float aver2=(float)sum2/h;
    printf("%.1f %.1f",aver1,aver2);
    free(ass1);
    free(ass2);
    return 0;
}

by bright_mountain @ 2024-12-06 20:40:10

@mopeicong谢谢佬,刚学malloc想多练点没用过的东西找问题、、


by bright_mountain @ 2024-12-06 20:53:05

@pies_0x又菜又爱练是这样的哈哈


by bright_mountain @ 2024-12-06 20:54:38

找到问题了,原来是分配动态内存长度的时候打成sizeof(int*)了


|