c编程求1到n的k次幂之和

2024-11-29 09:01:50
推荐回答(1个)
回答1:

#include 
#include 

int main ()
{
    unsigned long long nn=0,n=0,k=0,sum=0;
    printf("请输入底数 n:");
    scanf("%llu",&n);
    printf("请输入指数 K:");
    scanf("%llu",&k);
    
    nn = n;
    
    while(n > 0)
    {
        sum += (unsigned long long)pow(n, k);
        
        if(sum == 0)
        {
            printf("%llu 的 %llu 次方太大了,超出了unsigned long long的范围……\n",nn,k);
            return 0;
        }
        
        
        /**
         * 这种判断可能只有从1到n相加才会出现总和超出的情形
        if(sum == 0)
        {
            if((unsigned long long)pow(nn,k) == 0)
            {
                printf("%llu 的 %llu 次方太大了,超出了unsigned long long的范围……\n",nn,k);
                return 0;
            }
            printf("1 的 %llu 次幂到 %llu 的 %llu 次幂的总和超出了unsigned long long的范围……\n",k,nn,k);
            return 0;
        }
        **
        */
        
        n--;
    }
    
    printf("\n1 的 %llu 次幂到 %llu 的 %llu 次幂之和为:%llu\n",k,nn,k,sum);
    return 0;
}