求助大佬们,实在想不清楚问题的点

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

yuuhhh @ 2022-10-10 19:08:24


#include<stdio.h>
int main()
{int n,k,i,a,b;
scanf("%d %d",&n,&k);
double sum=0;
double sus=0;
for(i=1;i<=n;i++)
{if(i%k)
{sum+=i;
a++;}
else {sus+=i;b++;}}

printf("%.1lf %.1lf",sum/a,sus/b);
return 0;}

by wininaction @ 2022-10-10 19:40:11

  1. 变量要全局的,不然没初值
  2. i%k后加==0,否则返回的是i%k非零这个命题的真伪 代码:
    
    #include<stdio.h>
    int n,k,i,a,b;

int main() { scanf("%d %d",&n,&k); double sum=0; double sus=0; for(i=1;i<=n;i++) {if(i%k==0) {sum+=i; a++;} else {sus+=i;b++;}}

printf("%.1lf %.1lf",sum/a,sus/b); return 0;}


by 我是一个小号 @ 2022-10-10 19:41:10

@yuuhhh sum是B类数,sus是A类数

e.g.

若k=3,i=8

i%k==2,显然除不尽

sum+=8


by wininaction @ 2022-10-10 19:41:11

等等,这啥,代码再来一遍:

#include<stdio.h>
int n,k,i,a,b;

int main()
{
scanf("%d %d",&n,&k);
double sum=0;
double sus=0;
for(i=1;i<=n;i++)
{if(i%k==0)
{sum+=i;
a++;}
else {sus+=i;b++;}}

printf("%.1lf %.1lf",sum/a,sus/b);
return 0;
}

by CH_mengxiang @ 2022-10-10 19:44:08

你的a,b没有初始化为0,系统会赋一个很大的数

只有定义为全局变量的时候才会默认初始化为0


by CH_mengxiang @ 2022-10-10 19:46:58

@PRC_Dreamwastaken 而且您判断好像写反了


by yuuhhh @ 2022-10-10 19:47:51

@wininaction 非常感谢


by yuuhhh @ 2022-10-10 19:48:40

@PRC_Dreamwastaken 非常感谢,我已经改正并通过了


by yuuhhh @ 2022-10-10 19:49:21

@我是一个小号 感谢


|