0
上午運行這兩個函數做相同的計算「總結前N個整數」,然後比較每個運行時間。該程序工作正常與小輸入,但問題是,當我輸入像1000000大數字,它計算第一個方法「iterativeSum()」,然後一旦它到達recursiveSum()它停止工作。C++總和大數,程序停止?
我不確定,但你認爲這可能是因爲cout?
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void iterativeSum(int);
int RecursiveSum(int);
int main()
{
long long posInt;
std::cout << "Enter a positive integer: ";
std::cin >> posInt;
int start_s=clock();
iterativeSum(posInt);
int stop_s=clock();
int start_s1=clock();
cout << "\nThe recursive algorithm to sum the first N integers of "<< posInt << " is: "<< RecursiveSum(posInt) << endl;
int stop_s1=clock();
cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)/1000 << endl;
cout << "time: " << (stop_s1-start_s1)/double(CLOCKS_PER_SEC)/1000 << endl;
return 0;
}
void iterativeSum(int posInt)
{
//positive Integer >=0
int sum = 0;
//loop through and get only postive integers and sum them up.
// postcondion met at i = 0
for(int i = 0; i <= posInt;i++)
{
sum +=i;
}
//output the positive integers to the screen
std::cout <<"\nThe iterative algorithm to sum the first N integers of " <<posInt <<" is: " << sum << "\n";
}
int RecursiveSum(int n)
{
if(n == 1) // base case
{
return 1;
}
else
{
return n + RecursiveSum(n - 1); //This is n + (n - 1) + (n - 2) ....
}
}
您是否收到錯誤消息?或者該程序的運行時間真的很長?順便說一句:你應該添加C++標籤到這個問題 – Aemyl
在編譯器上沒有錯誤,運行時間太長了,所以windows一旦進入recusiveSum方法就會停止運行程序? euhh我不知道如何添加C++標籤,但對不起:D – Ivawen
沒問題,我現在添加它(但你必須接受編輯)。 – Aemyl