我收到了一项任务,要求编写一个递归函数,该函数从用户处接收两个整数:x
和 y
并打印出直到数字 x*y
。
函数的原型(prototype)必须与:void mult_table (int x, int base, int y)
(base
在第一次调用该函数时获取 1
)。
例如,如果 x=4
和 y=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. 我无法考虑该函数的停止情况,因为每次我要打印新行时,x
和 y
值都会更改。
我将非常感谢任何帮助,甚至是其他尝试方法的建议。
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
分解为 f1
和 f2
,这样 f1 * f2
就是您需要打印的内容步骤基础
。我可以给你公式,但由于这是一项作业,我选择只是为了给你一个提示:在表格中写下 base 的值以及 f1
和 f2
的预期值code> 然后你必须找到 2 个公式来根据 base
和 y
计算 f1
和 f2
。
例如(对于 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/