我對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;
}
調試器。使用調試器。調試器將使您能夠單獨執行每個語句並*觀察變量的值。使用調試器比發佈到StackOverflow並等待某人爲您使用調試器要快得多**。 –
'main'的返回應該是'int'而不是'void'。我建議閱讀如何調用函數。你所做的只是顯示函數指針。 –