计算序列的第n项。为什么我会收到编译器错误?

时间:2014-12-08 00:19:26

标签: c++ recursion

我将编写一个程序来计算由以下递归关系定义的序列的第n项。

S(1) = 2
S(n) = 2*S(n-1) + n*2^n

它将询问用户n的值,然后执行以下语句:

cout << "The " << n << "th term is " << findterm(n) << endl;

find term将是一个递归函数,用于确定第n个术语的值。

#include <iostream>
#include <math.h>
using namespace std;

long double findterm(long double);
long double in;

int main()
{
    clock_t begin;
    clock_t end;
    cout << "Enter number: ";
    cin >> in;
    begin = clock();
    cout << endl << "The " << in << "th term is " << findterm(in) << endl;
    end = clock();
    cout << (float)((float)end) - ((float)begin) / CLOCKS_PER_SEC << " TU." << endl;
    return 0;
}

long double findterm(long double n)
{
    float bn = 1;
    if( n == 1 )
    {
        return 2;
    }
    return((2*findterm(n-1)) + (n*pow(2, (double)n)));
}

为什么我会收到编译错误?

(6): error C2143: syntax error : missing ')' before ';'
(11): error C2065: 'clock_t' : undeclared identifier
(11): error C2146: syntax error : missing ';' before identifier 'begin'
(11): error C2065: 'begin' : undeclared identifier
(11): error C2065: 'end' : undeclared identifier
(17): error C2065: 'begin' : undeclared identifier
(17): error C3861: 'clock': identifier not found
(19): error C2065: 'end' : undeclared identifier
(19): error C3861: 'clock': identifier not found
(21): error C2065: 'end' : undeclared identifier
(21): error C2065: 'begin' : undeclared identifier
(21): error C2065: 'CLOCKS_PER_SEC' : undeclared identifier

1 个答案:

答案 0 :(得分:1)

您的代码无法编译的原因是您没有包含任何标准的时间相关库 只需包含 time.h ctime

#include <time.h>

此头文件包含获取和操作日期和时间信息的函数定义。