您的位置:首页 > 其它

用短路表达式在语法层面上替代条件判断语句

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: