我收到了一个写一个递归函数的赋值,它接收来自用户的两个整数:x
和y
并打印出乘法表,直到数字x*y
。
函数的原型设计必须完全像: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
}
}
答案 0 :(得分:1)
每次通话增加base
一个。然后,您必须将base
分解为f1
和f2
,这样f1 * f2
就是您需要在步骤base
打印的内容。我可以给你一个公式,但由于这是一个作业我选择只是给你一个提示:在表格中写下基数的值和f1
和f2
的预期值然后你有根据{{1}}和f1
找到2个计算f2
和base
的公式。
E.g。 (对于x = 4和y = 5):
y
提示:
base f1 f1
1 1 1
2 1 2
..
4 1 5
5 2 1
6 2 2
..
and so on
种循环。认为数学f2
(c中的mod
)就是这样的。%
每f1
次迭代增加一个k
。认为/
做了类似的事情。答案 1 :(得分:0)
编写两个递归函数,一个用于递归x
的值,另一个用于递归y
的值。
#include <stdio.h>
void mult_table_y(int x, int y)
{
if ( y != 1 )
{
mult_table_y(x, y-1);
}
printf("%d ", x*y);
}
void mult_table(int x, int y)
{
if ( x != 1 )
{
mult_table(x-1, y);
}
mult_table_y(x, y);
printf("\n");
}
int main()
{
mult_table(5, 5);
}