2017-03-10 56 views
0

我對C++相當陌生,並且正在嘗試編寫一個使用Do-While循環計算從1到n的和的程序,其中n是輸入參數,並且使用for循環中的階乘函數來計算n的階乘。但是,編譯程序時,我得到的結果如下:C++程序不會返回正確的階乘值

從1到n(其中n在本例中爲5)中的總數爲001ED2A8或其他奇怪的數字和字母組合。我的因子結果也會發生同樣的情況。我將不勝感激任何和所有的幫助,我可以得到。以下是我迄今爲止:

#include "stdafx.h" 
#include <iostream> 
using namespace std; 

int total(int); 
int factorial(int); 

void main() 
{ 
    int n; 
    cout << "Please enter a positive number:"; 
    cin >> n; 
    cout << "The total from 1 to " << n << "is " << total << endl; 
    cout << "The factorial of " << n << " is: " << factorial << endl; 
} 

int total (int n) 
{ 
    int i, total; 

    total = 0; 
    i = 1; 
    do 
    { 
     total = total + i; 
     i = i + 1; 
    } while (total <= n); 
    return total; 
} 

int factorial (int n) 
{ 
    int product = 1; 

    for (;n>0; n--) 
    { 
     product = n * product; 
    } 
    return product; 
} 
+2

調試器。使用調試器。調試器將使您能夠單獨執行每個語句並*觀察變量的值。使用調試器比發佈到StackOverflow並等待某人爲您使用調試器要快得多**。 –

+6

'main'的返回應該是'int'而不是'void'。我建議閱讀如何調用函數。你所做的只是顯示函數指針。 –

回答

0
long factorial (int n) 
{ 
if (n >= 1) 
    return n*factorial(n-1); 
else 
    return 1; 
} 

或使用循環當你使用如下

for(i=1,f=1;i<=n;i++) 
{ 
    {f=f*i;} 
} 
+0

這個問題正在尋找*解釋*,而不僅僅是工作代碼。您的回答對提問者沒有任何洞察力,並且可能會被刪除。請[編輯]解釋導致觀察到的症狀的原因。 –

0

cout << "The total from 1 to " << n << "is " << total << endl; 

它相當於

int (*function_ptr)(int) = total; 
cout << "The total from 1 to " << n << "is " << function_ptr << endl; 

您正在傳遞函數指針operator<<,而不是調用函數返回的值。

在該上下文中,函數指針被轉換爲布爾值true。因此,該呼叫相當於:

cout << "The total from 1 to " << n << "is " << true << endl; 

下一行發生同樣的事情。

要打印這些函數返回的值,必須進行函數調用。用途:

cout << "The total from 1 to " << n << "is " << total(n) << endl; 
cout << "The total from 1 to " << n << "is " << factorial(n) << endl; 

此外,你應該的main返回值更改爲int

int main() 
{ 
    ... 
} 
+0

啊,那是程序中的錯誤。我做了那個函數調用,現在它正常工作。感謝您的幫助和明確的解釋。 – mazeem74

+0

@ mazeem74,不客氣。 –

0
To use a for loop as follows: 
int f=1, i=1; 
for(i=1,f=1;i<=n;i++) 
{ 
    {f=f*i;} 
} 
+4

這個問題正在尋找*解釋*,而不僅僅是工作代碼。您的回答對提問者沒有任何洞察力,並且可能會被刪除。請[編輯]解釋導致觀察到的症狀的原因。 –