c ++使用加法递归地乘以2个整数 [英] c++ Recursively multiply 2 integers using addition

查看:54
本文介绍了c ++使用加法递归地乘以2个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为使用递归和加法将两个整数相乘的作业编写代码.但是,我目前收到很多错误消息,我什至不确定我是否走在正确的轨道上.而且,只是为了仔细检查,这是递归的,对吗?我为这个问题编写了另一个程序,它运行良好,直到我意识到它实际上并不是递归的.完整代码如下:

I'm trying to write code for homework that uses recursion and addition to multiply two integers together. But, I'm currently getting a lot of error messages, and I'm not even sure if I'm on the right track. And, just to double-check, this is recursive, right? I wrote another program for this problem which worked great until I realized it wasn't actually recursive. Here's the full code:

#include <iostream>
#include <iomanip>
using namespace std;
int result;
int m;
int n;

int rmultiply(int m, int n)
{
    if(n > 1)
        return(m + (rmultiply(n - 1)));

    else if ((m == 0) || (n == 0))
        return 0;
    else if (n == 1)
        return m;
}

int main(m, n)
    {
    cout << "Enter two integers to multiply" << endl; //prompt user to input 2 integers
    cin >> m >> n; //store them in variable m and n

    result = rmultiply(m,n);
    cout << result;
    }

错误 1:函数 'int rmultiply(int, int)' 的参数太少

Error 1: Too few arguments to function 'int rmultiply(int, int)'

return(m + (rmultiply(n - 1)));

警告:控制到达非空函数的结尾

Warning: control reaches end of non-void function

错误 2(对于下面的代码行):表达式列表在初始化程序中被视为复合表达式

Error 2(for code lines below): Expression list treated as compound expression in initializer

错误 3:应为 ',' 或 ';'之前'{'令牌

Error 3: Expected ',' or ';' before'{' token

警告:逗号运算符的左操作数无效

Warning: left operand of comma operator has no effect

int main(m, n)
{

任何帮助将不胜感激!

推荐答案

当你在这一行再次调用函数时,

When you are calling the function again in this line,

return(m + (rmultiply(n - 1)));

你必须传递另一个变量.

You have to pass another variable.

此外,将全局变量 m 和 n 命名为不同的名称也是个好主意.它不会影响编程,只是为了更好地理解.因为函数 rmultiply 中的 m 和 n 变量将始终与全局 m 和 n 不同(除非通过引用传递).

Also, it will be a good idea to name the global variables m and n something different. It wont affect the programming, but just for better understanding. Because the m and n variable inside function rmultiply will always be different than the global m and n (unless passed by reference).

对于其他错误,在行中定义一个变量类型,

For the other errors, define a type of variable in line,

main(m, n)

也许是一个整数.

并且,在 main 中确保返回一个整数.因为在函数定义中你有 int main

And, in the main make sure that an integer is returned. Because in the function definition you have int main

这篇关于c ++使用加法递归地乘以2个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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