用短路表达式在语法层面上替代条件判断语句
2015-10-19 15:09
459 查看
// testvc6.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <math.h> void fnTest(); int mul_n_subtract_1(int iInput); ///< 实现 n * (n - 1) int main(int argc, char* argv[]) { fnTest(); /** run results please input n:10 1*2*3*...*9*10 = 3628800 END, press any key to quit */ printf("END, press any key to quit\n"); getchar(); return 0; } void fnTest() { /** 不借助if-else, while, do-while, for, ?:, switch-case, goto, 来实现 1*2*3*...*n-1*n, (不考虑溢出问题) */ /** 这道题是在说,在语法层面, 怎么用短路表达式代替条件判断语句 */ /** 在C标准中,有这样的规定: 在“exp1 && exp2” 中如果exp1为false,则不再计算exp2的值 在“exp1 | | exp2” 中如果exp1为true,则不再计算exp2的值 这种机制被称为”逻辑短路“,一是为了优化,更重要的是为了提高代码的可移植性,避免产生二义性 */ char ch = '\0'; int iInput = 0; int iOut = 0; printf("please input n:"); scanf("%d", &iInput); /// scanf 的回车 0x0a, 留在了buffer里面, 用getchar()还能读的到, /// clear input buffer do { ch = getchar(); } while ((ch != EOF) && (ch != '\n')); iOut = mul_n_subtract_1(iInput); printf("1*2*3*...*%d*%d = %d\r\n", iInput - 1, iInput, iOut); } int mul_n_subtract_1(int iInput) { int iRc = 0; /// 在使用递归调用的判断上, 在语法层面,不是用条件判断语句 ((iRc = (1 == iInput)) ///< 如果 iInput == 1, 返回1 || (iRc = iInput * mul_n_subtract_1(iInput - 1))); ///< 否则返回 iInput * mul_n_subtract_1(iInput - 1) return iRc; }
相关文章推荐
- APP 接口开发及读取静态缓存
- [转] Nginx模块开发入门
- 冒泡排序(lua实现)
- 用到的专业词汇
- ES内部分片处理机制
- Avro 初识
- 开发购物车模块中遇到的问题
- Lucene入门
- java 中Int和Integer区别以及相关示例
- iOS 面试题汇总
- SpringMVC访问静态页面
- Java Servlet与Applet、CGI、JSP的比较
- Linux进程同步之记录锁(fcntl)
- Bind SQLi方法探究
- Linux下打包压缩成war包和解压war包
- 如何用C语言获取文件的大小
- 数据结构例程——以孩子兄弟链存储的树的高度
- 使用NotePad++录制宏功能如何快速将sql搜索条件加上前后单引号
- 程序员久坐不动的8大危害
- ZIP,RAR文件的contentType分别是什么?