博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
求1+2+…+n,要求不能使用乘除法、for、while、if、else...
阅读量:6996 次
发布时间:2019-06-27

本文共 407 字,大约阅读时间需要 1 分钟。

hot3.png

题目:

求1+2+…+n,

要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。

网上看到一种宏定义的写法不是很理解,还有一种递归的写法,很巧妙,学习了。

代码如下:

#include 
#include 
int sum(int n){    int tmp = 0;    (n)&&(tmp = sum(n-1));//当n=0时,不再执行(tmp = sum(n-1))    return n+tmp;}int main(void){    printf("1+2+...+100 = %d\n",sum(100));    return 0;}

关于那段宏定义,我再看看,稍后贴出

转载于:https://my.oschina.net/u/1470003/blog/224322

你可能感兴趣的文章