当前位置:嗨网首页>书籍在线阅读

16-递减运算符--

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

5.3.4 递减运算符: --

每种形式的递增运算符都有一个递减运算符(decrement operator)与之对应,用 -- 代替 ++ 即可:

--count; // 前缀形式的递减运算符
count--; // 后缀形式的递减运算符

程序清单5.12演示了计算机可以是位出色的填词家。

程序清单5.12  bottles.c 程序

#include <stdio.h>
#define MAX 100
int main(void)
{
     int count = MAX + 1;
     while (--count > 0) {
          printf("%d bottles of spring water on the wall, "
                    "%d bottles of spring water!\n", count, count);
          printf("Take one down and pass it around,\n");
          printf("%d bottles of spring water!\n\n", count - 1);
     }
     return 0;
}

该程序的输出如下(篇幅有限,省略了中间大部分输出):

100 bottles of spring water on the wall, 100 bottles of spring water!
Take one down and pass it around,
99 bottles of spring water!
99 bottles of spring water on the wall, 99 bottles of spring water!
Take one down and pass it around,
98 bottles of spring water!
...
1 bottles of spring water on the wall, 1 bottles of spring water!
Take one down and pass it around,
0 bottles of spring water!

显然,这位填词家在复数的表达上有点问题。在学完第7章中的条件运算符后,可以解决这个问题。

顺带一提, > 运算符表示“大于”,<运算符表示“小于”,它们都是关系运算符(relational operator)。我们将在第6章中详细介绍关系运算符。