- 知识讲解
- 课后习题
- 交替打印FooBar
在学习过循环之后,我们可以通过循环用字符去打印一些图像,只要我们计算好坐标即可。
例如:
#include课后习题 交替打印FooBarint main() { int n, i, j; while(~scanf("%d", &n)) { for(i = 1; i <= n; ++i) { // (1) for(j = 1; j <= i; ++j) // (2) printf("*"); // (3) printf("n"); // (4) } } return 0; }
题目链接:
1115. 交替打印FooBar
代码如下:
typedef struct {
int n;
sem_t sem1;
sem_t sem2;
} FooBar;
FooBar* fooBarCreate(int n) {
FooBar* obj = (FooBar*) malloc(sizeof(FooBar));
obj->n = n;
sem_init(&(obj->sem1), 0, 1);
sem_init(&(obj->sem2), 0, 0);
return obj;
}
void foo(FooBar* obj) {
for (int i = 0; i < obj->n; i++) {
sem_wait(&(obj->sem1));
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
sem_post(&(obj->sem2));
}
}
void bar(FooBar* obj) {
for (int i = 0; i < obj->n; i++) {
sem_wait(&(obj->sem2));
// printBar() outputs "bar". Do not change or remove this line.
printBar();
sem_post(&(obj->sem1));
}
}
void fooBarFree(FooBar* obj) {
sem_destroy(&(obj->sem1));
sem_destroy(&(obj->sem2));
free(obj);
}


![[题解]《C语言入门100例》(第16例) 打印字符 [题解]《C语言入门100例》(第16例) 打印字符](http://www.mshxw.com/aiimages/31/529062.png)
