C - 使用数组计算大数 a^b 的幂

标签 c

问题由两个数字a和b组成,答案是a^b的数字之和。

我写了下面的代码。它在所有情况下都给出正确的结果。但是当输入是这样的 < b 时,在给出正确答案后,我遇到了段错误。

我尝试了很多调试方法,但无法确定问题所在。任何帮助将不胜感激。

提前致谢..!

#include<stdio.h>

void power (int, int, int *product);
int main()
{
    int a,b,product[200];
    scanf("%d %d",&a, &b);
    power(a,b,product);
    return 0;
}

void power(int a, int b, int *product)
{
    int i,m,j,x,temp,sum=0;
    int *p = product;
    *(p+0)=1; //initializes array with only 1 digit, the digit 1
    m=1; // initializes digit counter
    temp=0; //Initializes carry variable to 0.
    for(i=1;i<=b;i++)
        {
            for(j=0;j<m;j++)
            {
               x = (*(p+j))*a+temp;
               *(p+j)=x%10; 
               temp = x/10; 
            }
             while(temp>0) //while loop that will store the carry value on array.
             { 
               *(p+m)=temp%10;
               temp = temp/10;
               m++; 
             }
    }
    //Printing result
    for(i=m-1;i>=0;i--) 
              sum = sum + *(p+i);
    printf("\n%d",sum);
              printf("\n");
}

最佳答案

我希望下面的代码能够完成您想要做的事情。这很简单,而且看起来也不错。

#include<stdio.h>

void power (int, int);
int main()
{
   int a,b;
   scanf("%d %d",&a, &b);
   power(a,b);
   return 0;
}

void power(int a, int b)
{
   int c=1,sum=0;
   while(b>0)
   {   
      c = c*a;
      b--;
   }   
   printf("%d\n",c);
   while(c!=0)
   {   
      sum = sum+(c%10);
      c =c/10;
   }   
   printf("%d\n",sum);

}

关于C - 使用数组计算大数 a^b 的幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26243564/

相关文章:

c - 检测 C 中的空标记

c++ - C 程序的执行方式与 shell 不同

c - strcat 和段错误 11

c - 在单个 Pthread 中打印

c - MicroChip dsPic33,UART RX 中断未被调用

ios - Xcode 8 更新后,通过桥接 header 的 .c 文件不起作用

c - 关于数组和指针

c++ - 为什么这个矩阵乘法代码不起作用

c - 字符串搜索 u_char*

c - 使用 _finddata_t->name 浏览子目录