【发布时间】:2014-05-17 18:13:23
【问题描述】:
我收到了一个任务,要编写一个递归函数,该函数从用户那里接收两个整数: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
}
}
【问题讨论】:
标签: c recursion multiplication