讨论:不用递归不用循环求1-100的和
在百度里面看到的,但是答案都是借用一些函数来实现的。
请问,能不能用算法解决这个问题啊??
我只是好奇,顺便扩展一下自己的思路。
[解决办法]
? 不用递归,不用循环,就直接用函数(公式)呗;
1+2+...+n = (1+n)*n/2;
归纳出函数(公式),是算法的最高境界;
难道lz认为函数不是算法?
[解决办法]
对头,函数也是算法嘛。
[解决办法]
不用递归不用循环求1-100的和
return n*(n+1) /2
[解决办法]
up
[解决办法]
- C/C++ code
//那用控制goto语句:#include<iostream>using namespace std;int main(){ int sum=0; int n=1;L: sum+=n; n++; if(n<=100) goto L; cout<<sum; return 0;}
[解决办法]
呵呵,不循环不递归只能归纳出规律了,支持n*(1+n)/2
[解决办法]
请楼主详细说明一下什么是不用循环不用函数,这样讨论下去才有意义。上面有人用了GOTO,GOTO不是循环么?
[解决办法]
[解决办法]
[解决办法]
可以在类的构造函数里实现。
#include<iostream>
using namespace std;
class test
{
public:
test();
int GetSum();
private:
static int N;
static int SUM;
};
int test::N=0;
int test::SUM=0;
test::test()
{
N++;
SUM+=N;
}
int test::GetSum()
{
return SUM;
}
void main()
{
int n;
int result;
cout<<"Please input a number"<<endl;
cin>>n;
test *a=new test[n];
delete[] a;
a=NULL;
result=a->GetSum();
cout<<result<<endl;
}
[解决办法]
对于数值类的计算,如果已知具体的数据集,完全可以用模板元编程来实现。
- C/C++ code
#include <iostream>template<unsigned int N>struct A{ enum { value = A<N-1>::value + N };};template<>struct A<1>{ enum { value = 1; };};int main({ std::cout<<A<100>::value<<std::endl; return 0;}
[解决办法]
i=1;
i+=2;
i+=3;
...
i+=100;
printf("%d\n", i);
不就行了