编写函数 void stars( unsigned int n); 打印输出n个‘*’ 字符。 比如执行 stars(5)时,输出结果为: *****
时间: 2023-12-06 12:05:43 浏览: 31
以下是实现函数void stars(unsigned int n)的代码:
```c
#include <stdio.h>
void stars(unsigned int n) {
if (n == 0) {
return;
}
printf("*");
stars(n - 1);
}
int main() {
unsigned int n = 5;
stars(n);
return 0;
}
```
以上代码中,函数stars()使用递归的方式输出n个星号。当n等于0时,函数返回。否则,函数输出一个星号,然后递归调用自身,传入n-1作为参数。这样,每次递归调用都会输出一个星号,直到n等于0时,函数返回。
执行stars(5)时,输出结果为:*****
相关问题
编写程序unsigned int getlen(char *s); 返回字符串s的⻓度。
可以使用循环来遍历字符串,直到遇到字符串结尾符 `\0`,统计遍历过的字符个数即为字符串的长度。具体实现如下:
```c++
#include <iostream>
unsigned int getlen(char *s)
{
unsigned int len = 0;
while (*s != '\0') {
len++;
s++;
}
return len;
}
int main()
{
char str[] = "hello world";
unsigned int len = getlen(str);
std::cout << "The length of string \"" << str << "\" is " << len << std::endl;
return 0;
}
```
输出结果为:
```
The length of string "hello world" is 11
```
上面的程序中,使用了一个 while 循环来遍历字符串 s。循环条件为 *s != '\0',即只要当前字符不是字符串结尾符,就继续遍历。在循环中,每遍历一个字符,就将字符串长度 len 加一。最后返回字符串长度 len 即可。
char* UInt32toStr(unsigned int n)
这是一个 C/C++ 函数,用于将无符号整数转换为字符串。函数声明如下:
```c++
char* UInt32toStr(unsigned int n);
```
函数的参数是一个无符号整数 `n`,返回值是一个指向字符数组的指针,该字符数组包含了 `n` 的字符串表示。
函数实现可以参考下面的代码:
```c++
#include <stdio.h>
#include <stdlib.h>
char* UInt32toStr(unsigned int n) {
// 最多需要 10 个字符
char *str = (char *) malloc(11 * sizeof(char));
sprintf(str, "%u", n);
return str;
}
```
该函数使用了标准库函数 `sprintf` 将整数转换为字符串,并使用动态内存分配来分配足够的空间来存储该字符串。需要注意的是,返回的字符数组需要在使用完毕后手动释放内存,以避免内存泄漏。