两个样例我试了都正确,为什么全WA

P2669 [NOIP2015 普及组] 金币

Lilindong @ 2024-07-29 20:33:34

#include<stdio.h>
int main()
{
    int k,v=0,n=0,sum=0,i,su;
    scanf("%d",&k);
    while(v<=k)
    {
        n++;
        v+=n;
    } 
    for(i=1;i<n;i++)
    {
        su+=i;
        sum+=i*i;
    }
    printf("%d",sum+(k-su)*n);
    return 0;
}

by yangduan_ @ 2024-07-29 20:38:04

@Lilindong su 没赋初始值

#include<stdio.h>
int main()
{
    int k,v=0,n=0,sum=0,i,su=0;
    scanf("%d",&k);
    while(v<=k)
    {
        n++;
        v+=n;
    } 
    for(i=1;i<n;i++)
    {
        su+=i;
        sum+=i*i;
    }
    printf("%d",sum+(k-su)*n);
    return 0;
}

by Lilindong @ 2024-07-29 20:40:08

@yangduan_ 谢谢大佬


by yangduan_ @ 2024-07-29 20:40:09

@Lilindong 建议以后用全局变量,这样每个数的初始值就是0,就不用再赋值一遍了

#include<stdio.h>
int k,v,n,sum,su;
int main()
{
    int i;
    scanf("%d",&k);
    while(v<=k)
    {
        n++;
        v+=n;
    } 
    for(i=1;i<n;i++)
    {
        su+=i;
        sum+=i*i;
    }
    printf("%d",sum+(k-su)*n);
    return 0;
}

by Lilindong @ 2024-07-29 20:43:38

@yangduan_ 谢谢大佬,我现在才知道可以设全局变量,关注啦


by guoyanwei120223 @ 2024-08-13 17:47:39

#include<bits/stdc++.h> 
using namespace std;
int main()
{
    int k,jb=0,cnt=0,n=0;
    cin>>k;
    for(int i=1;i<=k;i++)
    {

        cnt++;
        for(int j=1;j<=cnt;j++)
        {
            n++;
            jb+=cnt;
            if(n==k) break;
        }
        if(n==k) break;
    }
    cout<<jb;
    return 0;
}

@Lilindong


|