首页 > 解决方案 > 如何在没有“pow”的情况下实现 a^b?

问题描述

我需要编写一个函数来计算 a^b 但我不允许使用pow. 有任何想法吗?我搞不清楚了。看起来问题现在很重要......在某个地方,我的特点是 vys。因此,如果我在 main 中设置 vys=1,我会在输出中得到 1..

#include <stdio.h>
#include <time.h>
#include <math.h>
#include <unistd.h>

void multiplied(int b, int n)
{
  int i=1, vys=1;
  while (i<=n)
  {
    vys *=b;

    i++;
  }
  return vys;
}


main(void)
{
  int b=0, n=0, vys=1;
  printf("Give numbers b and n but they must be in interval <0,10>!\n");
  scanf("%d %d", &b, &n);
  if ((b < 0 || b>10) || (n<0 || n>10))
  {
    printf("Numbers are not in interval <0,10>!\n");
  }
  else
  {
    printf("Number is in interval so i continue...\n");
    sleep(2);
   vys= multiplied(&b, &n);
    printf("%d", vys);
}

标签: c

解决方案


让我们明确一点。

首先,这

void multiplied(int *b, int *n)

返回一个int,所以这么说。

int multiplied(int *b, int *n)

接下来,您在 main 中初始化变量:在此处执行相同操作。

  int i, vys;

像这样:

  int i=1, vys=1;

现在让我们看一下循环:

  while (i<=n)
  {
    vys=*b**b;

    i++;
  }

就目前而言,您vys在循环中一遍又一遍地设置某些东西。您想乘以,例如 2,然后是 2*2,然后是 2*2*2,......如果您想要 2 的幂:

  while (i<=n)
  {
    vys *= *b;

    i++;
  }

现在,您不需要传递指针。

int multiplied(int b, int n)
{
  int i=1, vys=1;
  while (i<=n)
  {
    vys *= b;

    i++;
  }
  return vys;
}

编辑:

调用函数时要注意:

main(void)
{
   int b=0, n=0, vys;

   //input and checking code as you have it

    multiplied(&b, &n); //<---- return ignored
    printf("%d", vys); //<-- print uninitialsed local variable
}

改变你最后两行:

    vys = multiplied(&b, &n); //<---- return captured
    printf("%d", vys); //<-- print returned variable

编辑2:

随着在函数中使用而不是指针的更改int,传递整数而不是它们的地址:

    vys = multiplied(b, n); //<---- pass the ints not their addresses
    printf("%d", vys); //<-- print returned variable, which should vary now

推荐阅读