使用递归将一个基数提高到其指数 - C ++ [英] Using Recursion to raise a base to its exponent - C++

查看:111
本文介绍了使用递归将一个基数提高到其指数 - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想写一些使用函数递归来提高基数的代码。我知道递归不是最好的方式来做的事情在C + +,但我只是想探索的概念有点。程序询问用户一个基数和指数,然后控制输出答案。这是我写的程序:

  #include< iostream> 
#include< math.h>
using namespace std;

int raisingTo(int,int);
int main()
{
int base,exponent;
cout<< 输入基本值:;
cin>>基础;
cout<< Enter exponent value:;
cin>>指数;
int answer = raisingTo(base,exponent);
cout<< 答案是:< answer<< endl;
char response;
cin>>响应;
return 0;
}

int raiseTo(int base,int exponent)
{
if(exponent> 0)
return 1;
else if(exponent = 0)
{
int answer =(int)pow((double)base,raisingTo(base,(exponent -1)));
return answer;有趣的是,当我运行这个程序时,你可以使用一个程序来创建一个新的程序,它不断返回答案为'1'!

解决方案

  int raisingTo(int base,unsigned int指数)
{
if(exponent == 0)
return 1;
else
return base * raisingTo(base,exponent - 1);
}

您有三个主要问题:




  • 您不必使用pow函数

  • 要比较数字,您应该使用 == = 是不比较的分配。

  • 您错过了如果指数等于0, li>

I simply want to write some code that makes use of recursion of functions to raise a base to its power. I know that recursion is not the most right way to do things in C++, but I just want to explore the concept a bit. The program asks the user for a base and an exponent and then console outs the answer. Here's the program I've written:

#include <iostream>
#include <math.h>
using namespace std;

int raisingTo(int, int);
int main()
{
    int base, exponent;
    cout << "Enter base value: ";
    cin >> base;
    cout << "Enter exponent value: ";
    cin >> exponent;
    int answer = raisingTo(base, exponent);
    cout << "The answer is: " << answer << endl;
    char response;
    cin >> response;
    return 0;
}

int raisingTo(int base, int exponent)
{
    if (exponent > 0)
        return 1;
    else if (exponent = 0)
    {
        int answer = (int) pow((double)base, raisingTo(base, (exponent - 1)));
        return answer;
    }
}

The funny thing is, when I run this program, it keeps returning the answer as '1'! Can someone please help me on this?

解决方案

int raisingTo(int base, unsigned int exponent)
{
    if (exponent == 0)
        return 1;
    else
        return base * raisingTo(base, exponent - 1);
}

You have 3 main problems:

  • You don't have to use pow function
  • To compare number you should use == as = is an assignment not compare.
  • You missed that if exponent is equal 0 you should return 1.

这篇关于使用递归将一个基数提高到其指数 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆