C语言用一个主函数调用age函数,求得第5个学生的年龄
时间: 2024-03-03 15:50:02 浏览: 32
好的,您可以参考下面的代码实现:
```c
#include <stdio.h>
int age(int n); // 函数声明
int main() {
int age5 = age(5); // 调用age函数,求得第5个学生的年龄
printf("第5个学生的年龄是:%d\n", age5);
return 0;
}
int age(int n) { // 函数定义
int age1 = 18; // 第1个学生的年龄
for (int i = 2; i <= n; i++) { // 从第2个学生开始遍历
age1 += 2; // 每个学生年龄比上一个学生大2岁
}
return age1;
}
```
程序中定义了一个 `age` 函数,用于求第 `n` 个学生的年龄。在 `main` 函数中调用 `age` 函数,传入参数为 `5`,即求第5个学生的年龄。在 `age` 函数中,我们使用一个变量 `age1` 来表示第1个学生的年龄,然后通过一个循环,遍历到第 `n` 个学生,每个学生的年龄比上一个学生大2岁。最后返回第 `n` 个学生的年龄。
相关问题
用C语言写一个调用当前时间的程序,用主函数调用这个时间函数
可以使用C语言中的time和ctime函数来获取和格式化当前时间。下面是一个示例程序,主函数调用了获取时间的函数:
```c
#include <stdio.h>
#include <time.h>
void print_current_time() {
time_t current_time = time(NULL);
char* c_time_string = ctime(¤t_time);
printf("Current time is: %s", c_time_string);
}
int main() {
print_current_time();
return 0;
}
```
在这个程序中,我们定义了一个名为print_current_time的函数,用于获取和输出当前时间。主函数调用了这个函数,来打印当前时间。
用C语言编写一个实现 strlen函数功能的函数,并试用主函数调用。
可以用以下代码实现:
```c
#include <stdio.h>
int my_strlen(char *str) {
int len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}
int main() {
char str[100];
printf("请输入字符串:");
scanf("%s", str);
int len = my_strlen(str);
printf("字符串长度为:%d\n", len);
return 0;
}
```
这里我们定义了一个 `my_strlen` 函数,它的参数是一个字符指针,返回值是字符串的长度。在函数内部,我们定义了一个变量 `len` 来存储字符串的长度,然后通过循环遍历字符串中的每个字符,每遍历一个字符 `len` 的值就加一,直到遍历到字符串的结尾为止。最后,我们返回 `len` 的值作为字符串的长度。
在主函数中,我们定义了一个字符数组 `str` 来存储用户输入的字符串,然后调用 `my_strlen` 函数来计算字符串的长度,并将结果输出到屏幕上。