簡體   English   中英

C ++程序未返回正確的階乘值

[英]C++ Program does not return the correct factorial value

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

從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;
}
long factorial (int n)
{
if (n >= 1)
    return n*factorial(n-1);
else
    return 1;
}

或如下使用for循環

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

使用時

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()
{
   ...
}
To use a for loop as follows: 
int f=1, i=1;
for(i=1,f=1;i<=n;i++)
{
   {f=f*i;}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM