程序 短路表

(短路表)
// 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值