001、不使用对象式宏
[root@localhost test]# ls test.c [root@localhost test]# cat test.c ## 测试程序 #include <stdio.h> int main(void) { int i, sum = 0; int v[5] = {3, 8, 2, 4, 6}; ## 定义int【5】 型数组 for(i = 0; i < 5; i++) { sum += v[i]; } printf("sum = %5d\n", sum); printf("mean = %.5f\n", (double)sum/5); ## 求和和均值 return 0; } [root@localhost test]# gcc test.c ## 编译 [root@localhost test]# ls a.out test.c [root@localhost test]# ./a.out ## 执行程序 sum = 23 mean = 4.60000
002、使用对象式宏
[root@localhost test]# ls test.c [root@localhost test]# cat test.c ## 测试程序 #include <stdio.h> #define NUMBER 5 // 定义对象式宏 int main(void) { int i, sum = 0; int v[NUMBER] = {3, 8, 2, 4, 6}; //在程序中使用NUMBER宏 for(i = 0; i < NUMBER; i++) { sum += v[i]; } printf("sum = %5d\n", sum); printf("mean = %.5f\n", (double)sum/NUMBER); return 0; } [root@localhost test]# gcc test.c -o kkk ## 编译程序 [root@localhost test]# ls kkk test.c [root@localhost test]# ./kkk sum = 23 mean = 4.60000
。
对象式宏不就是个变量替换嘛?
003、替代方法
[root@localhost test]# ls test.c [root@localhost test]# cat test.c ## 测试程序 #include <stdio.h> int main(void) { int i, sum = 0; int NUMBER; NUMBER = 5; int v[NUMBER] = {3, 4, 5, 8, 3}; // 数组数量用变量无法进行初始化,为什么? 此处必须使用对象式宏, 优势? for(i = 0; i < NUMBER; i++) { sum += v[i]; } printf("sum = %5d\n", sum); printf("mean = %.5f\n", (double)sum/NUMBER); return 0; } [root@localhost test]# gcc test.c -o kkk ## 无法正常编译 test.c: In function ‘main’: test.c:8:9: error: variable-sized object may not be initialized 8 | int v[NUMBER] = {3, 4, 5, 8, 3}; | ^~~
。
标签:对象,sum,NUMBER,C语言,int,test,root,localhost From: https://www.cnblogs.com/liujiaxin2018/p/18446475