斯坦福C ++课程。高斯的童年

时间:2016-03-31 18:08:36

标签: c++ c++11 gcc

我在这里做Standford C ++课程。

练习03从读者练习。这是给出的问题:

  

练习03计算1到100之间的数字之和。

/*
    As mathematical historians have told the story, the German mathematician
    Karl Friedrich Gauss (1777-1855) began to show his mathematical talent 
    at a very early age. When he was in elementary school, Gauss was asked by
    his teacher to compute the sum of the numbers between 1 and 100. Gauss is
    said to have given the answer instantly: 5050. Write a program that computes
    the answer to the question Gauss’s teacher posed.
 */   

执行此程序时遇到的错误是this => Guassian.cpp:在函数'int main()'中: Guassian.cpp:29:12:错误:无效使用非静态成员函数  ob1.sumodds;

怎么了?

#include<iostream>
using namespace std;

class Guassian
{


public:

int sumodds ( int  last )
{
    int result =    0;
    int odd = 1;
    for ( int i =    0; i < last; i++ ) 
    {
        result +=   odd;
        odd += 2;
    }
    return            result ;

}

};

int main()
{
Guassian ob1;
ob1.sumodds;
//return 0;
}

1 个答案:

答案 0 :(得分:2)

卡尔·弗里德里希·高斯可能没有像你那样计算它。此外,问题的正确答案是

#include <iostream>

int sum(int n)
{
  return n*(n+1)/2;
}

int main()
{
  std::cout << sum(100) << '\n';
}

如果你以类似的方式使用你的函数,你实际上会计算last的总和 - 很多奇数。请参阅here

我不确定你是否想要这个。