在数组中累积“数”的幂

时间:2016-08-22 09:42:26

标签: c

我在程序中得到了一个公式,它依赖于在数组中累加数字的幂。我在其他页面上注册了这个,但它不是我需要的:

   #include <stdio.h>
   #include <math.h>
   int main (){
   int x, y, powernumber;
   scanf ("%d %d",&x,&y);
   powernumber = pow(x,y);
   printf ("Powernumber = %d",powernumber);
   return 0;}

没关系,但我必须为每个电源号码分配一个插槽。

手头的问题是:

   int array [100];
   int i, int1;

   scanf ("%d",&int1);
   for (i=0; i<=100; i++)
   {array [i] = 1 / pow(2, int1); // <-----------------ERROR
   printf ("%d %d\n",i+1,array [i]);}
   return 0;}

公式的一点是,用户键入一个数字,并且每次循环进行一次循环时,此数字将作为powernumber累积,直到循环在i = 100处终止。假设用户输入数字3.第一次程序执行2 ^ 3,然后下一次2 ^ 4,然后是2 ^ 5,在数组中。它适用于乘法和除法等普通运算符,但不适用于幂号。上面的示例是一个剥离版本,因此它可能适用于编译器。但希望这个问题是可以理解的。

3 个答案:

答案 0 :(得分:0)

获取您需要执行的电源号码:

array [i] = (pow(2, int1));

要使用除法,您需要使用浮点数组和浮点数表示。还需要打印为%f而不是%d:

float array [100];
int i;
float int1;
scanf ("%d",&int1);
for (i=0; i<=100; i++)
{
    array [i] = 1.0 / pow(2.0, int1);
    printf ("%d %f\n",i+1,array [i]);
}
return 0;}

答案 1 :(得分:0)

我在这里找到了一个方法:Change int array to float array in C

以及我将在此打印的例程版本作为感激之情。

   #include <stdio.h>
   #include <math.h>
   //1D_Array(float). Create array, then divide 2 numbers and display sum.
   //KHO2016.no3. mingw (TDM-GCC-32) . c-ansi .
   int main()
   {
   //Declare
   int i,int1;
   float flp1,flp2,flp3,array[30];

   //valuate
   printf ("The program request 4 numbers\n");
   printf ("1. Number of Rows or loops\n2. Value above the fraction line\n");
   printf ("3. Value beneath the fraction line\n4. Value of Powernumber\n\n");

   jump :
   printf ("Type in number of loops, 1-30 :");
   scanf ("%d",&int1);
   if (int1>31)
   {printf ("Number is too large\n");
   goto jump;}

   else if (int1<=30)
   printf ("Type the number Above the Fraction line (Dividend) ");
   scanf ("%f",&flp1);
   printf ("Type the number beneath the Fraction line (Divisor) ");
   scanf ("%f",&flp2);
   printf ("Value of Powernumber ");
   scanf ("%f",&flp3);

   //calculate
   for (i<0;i<=int1-1;i++)
   {array[i]=(float)(flp1/pow(flp2, (++flp3)-1)); // <------ interesting part !
   printf ("Row [%d]\t%.0f / %.0f^%.0f = %.6f\n",i+1,flp1,flp2,flp3-1,(float)array[i]);}

   //terminate
   return 0;
   }

答案 2 :(得分:-1)

感谢。对于初学者来说,这有助于做到这一点

   for (i=0; i<=100; i++)
   {array [i] = 1 / (pow(2, int1++));

而且我认为我把它排序了。我现在遇到的一个问题是在数组中获取浮点数。该阵列完成了预期的工作。但是在这里:

   float int1;
   printf ("%d %f\n",i+1,array [i]);
   // The array refuse to be display floating numbers.
   //If the array is defined as a Float it also refuses.