逐行解释代码
explain the code line by line
我在 C 中找到了这段反转字符串的代码。此代码使用递归,我无法理解 reverse() 函数。谁能帮忙。
#include <stdio.h>
void reverse() //recursive function to reverse string.
{
char c;
scanf("%c",&c);
if(c!='\n')
{
reverse();
printf("%c",c);
}
}
void main()
{
printf("\nenter a string: ");
reverse();
getch();
}
reverse
函数以相反的顺序打印 char *
/字符串,例如"question" -> "noitseuq".
它通过逐个字符地读取输入字符串(scanf
一次只读取一个字符)并在 before 上调用下一个字符来实现当前字符。
如果交换 reverse();
和 printf("%c",c);
,您会注意到它打印下一个字符 在 当前字符之后,因此顺序与输入。关键是它在打印之前递归以颠倒字符顺序。
#include <stdio.h>
void reverse() //recursive function to reverse string.
{
char c; //declare a character
scanf("%c",&c); //scan that is get input from user in format scanf("format specifiers",&value1,&value2,.....);
if(c!='\n') //check if the character is blank
{
reverse(); //if blank call the method reverse() again to get get input which is not blank
printf("%c",c); //it will print the character from last letter to first when it is not blank
}
}
void main()
{
printf("\nenter a string: "); //skips a line and asks user to enter a string
reverse(); //calls method reverse()
getch();
}
在您的代码中,if(c!='\n') 这意味着直到遇到新行,if 语句才会执行。所以它将接受输入直到遇到 \n 。
然后如果 c=\n 将执行 printf 语句,它将打印输入字符串的最后一个字符。将此递归视为 Stack 的示例。
我在 C 中找到了这段反转字符串的代码。此代码使用递归,我无法理解 reverse() 函数。谁能帮忙。
#include <stdio.h>
void reverse() //recursive function to reverse string.
{
char c;
scanf("%c",&c);
if(c!='\n')
{
reverse();
printf("%c",c);
}
}
void main()
{
printf("\nenter a string: ");
reverse();
getch();
}
reverse
函数以相反的顺序打印 char *
/字符串,例如"question" -> "noitseuq".
它通过逐个字符地读取输入字符串(scanf
一次只读取一个字符)并在 before 上调用下一个字符来实现当前字符。
如果交换 reverse();
和 printf("%c",c);
,您会注意到它打印下一个字符 在 当前字符之后,因此顺序与输入。关键是它在打印之前递归以颠倒字符顺序。
#include <stdio.h>
void reverse() //recursive function to reverse string.
{
char c; //declare a character
scanf("%c",&c); //scan that is get input from user in format scanf("format specifiers",&value1,&value2,.....);
if(c!='\n') //check if the character is blank
{
reverse(); //if blank call the method reverse() again to get get input which is not blank
printf("%c",c); //it will print the character from last letter to first when it is not blank
}
}
void main()
{
printf("\nenter a string: "); //skips a line and asks user to enter a string
reverse(); //calls method reverse()
getch();
}
在您的代码中,if(c!='\n') 这意味着直到遇到新行,if 语句才会执行。所以它将接受输入直到遇到 \n 。 然后如果 c=\n 将执行 printf 语句,它将打印输入字符串的最后一个字符。将此递归视为 Stack 的示例。