C和指针第二章基础回顾
2.8编程练习1
#include <stdio.h>
#include <stdlib.h>
extern int increment(int);
extern int negate(int);
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int value1=increment(10);
int value2=negate(-10);
printf("%d\n",value1);
printf("%d",value2);
return 0;
}
// increment.c int increment(int value) { return value + 1; }
// negate.c int negate(int value) { return -value; }
1结果:
2.8编程练习2
#include <stdio.h>
int main() {
int balance = 0; // 初始化计数器
char c;
// 循环读取输入直到EOF
while ((c = getchar()) != EOF) {
if (c == '{') { // 如果是左花括号,计数器加一
balance++;
}
else if (c == '}') { // 如果是右花括号,计数器减一
balance--;
// 如果计数器变成负数,说明右花括号没有匹配的左花括号
if (balance < 0) {
printf("Mismatched braces found.\n");
return 1;
}
}
}
// 如果计数器在输入结束后不是零,说明有未匹配的左花括号
if (balance != 0) {
printf("Mismatched braces found.\n");
return 1;
}
printf("All braces are correctly matched.\n");
return 0;
}