c - 使用无循环递归的乘法表

标签 c recursion multiplication

我收到了一项任务,要求编写一个递归函数,该函数从用户处接收两个整数:xy 并打印出直到数字 x*y。 函数的原型(prototype)必须与:void mult_table (int x, int base, int y) (base 在第一次调用该函数时获取 1)。 例如,如果 x=4y=5,输出将为:

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20

请注意,函数内部不能使用循环,但如果需要,可以使用其他递归函数。

我的问题是: 1.如何在第2行及更多行中正确迭代基数,因为在第1行中简单的++可以工作,但对于第二行我已经需要 2. 我无法考虑该函数的停止情况,因为每次我要打印新行时,xy 值都会更改。 我将非常感谢任何帮助,甚至是其他尝试方法的建议。

void mult_table (int x, int base, int y)
{
    int temp; //temp variable to hold x vlaue
    if (base <= y) //as long as base is less or equal to y, a number of line will be printed
    {
        printf(" %d", base); //using base with +1 incrementation
        mult_table(x, base+1, y);
    }
    else
    {
        printf("\n"); //start of a new line
        temp = x; //value of x is saved because it will be changed but it is still needed
        x= x+x*(1/(base-temp-1)); //new x value x+(x*1/original base of line) to reach the next x value
        y = y+y*(1/(base-temp-1)); //new y value y+(y*1/original base of line) to reach the next x value
        base = base - temp; //base is incrimented by 1 using this calcualtion
        mult_table(x, base, y); //recursdive call
    }
}

最佳答案

每次调用将base加一。然后,您必须将 base 分解为 f1f2,这样 f1 * f2 就是您需要打印的内容步骤基础。我可以给你公式,但由于这是一项作业,我选择只是为了给你一个提示:在表格中写下 base 的值以及 f1f2 的预期值code> 然后你必须找到 2 个公式来根据 basey 计算 f1f2

例如(对于 x=4 和 y=5):

base  f1  f1
  1    1   1
  2    1   2
    ..
  4    1   5
  5    2   1
  6    2   2
    ..
and so on

提示:

  • 请注意,f2 是围绕一个范围进行循环的。认为数学 mod(c 中的 %)会做类似的事情。
  • 请注意,每 k 次迭代,f1 都会增加 1。认为 / 做了类似的事情。

关于c - 使用无循环递归的乘法表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23714600/

相关文章:

c++ - 算法的递归关系

c++ - 在 CUDA 上乘以两个 float 变量

c++ - 奇怪的乘法结果

c - 如何使指针在新结构中兼容?

c - 为什么要检查函数中 fscanf 返回值 < 1?

python - Python 为对象引用打印 "[...]"是什么意思?

python - 计算 1 到 n 之和的递归函数?

c++ - 如何在 C++ 中进行 32 位十进制 float 乘法?

arrays - 函数中 str[strlen(src)+1] 和 char *str=(char*)malloc((strlen(src)+1)*sizeof(char)) 的区别

c++ - 返回类型 int 的函数默认返回值 1?