qfedu-linux-advanced-level/day6/homework/h3.c

51 lines
896 B
C
Raw Permalink Normal View History

2023-08-21 22:01:14 +08:00
// 编写一个程序, 创建一个线程, 该线程计算并打印斐波那契数列的前n项, n由用户输入
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h> // atoi
void *fibonacci(void *data)
{
int n = *((int *)data);
int a = 1, b = 1, c;
if (n >= 1)
{
c = a;
printf("%d\t", c);
}
if (n >= 2)
{
c = b;
printf("%d\t", c);
}
int temp = n - 2;
while (n > 2 && temp > 0)
{
c = a + b;
a = b;
b = c;
temp--;
printf("%d\t", c);
}
printf("\n");
return NULL;
}
int main(int argc, char const **argv)
{
if (argc != 2)
{
printf("用法: %s 数字\n", argv[0]);
return 0;
}
int input = atoi(argv[1]);
pthread_t tid;
pthread_create(&tid, NULL, fibonacci, (void *)&input);
pthread_join(tid, NULL);
return 0;
}