【问题标题】:C++ Program does not return the correct factorial valueC++ 程序没有返回正确的阶乘值
【发布时间】:2017-03-10 03:33:30
【问题描述】:

我是 C++ 的新手,正在尝试编写一个程序,该程序使用 Do-While 循环来计算从 1 到 n 的总和,其中 n 是输入参数,并在 for 循环中使用阶乘函数来计算n 的阶乘。但是,当程序编译时,我得到如下结果:

从 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。我建议阅读如何调用函数。您所做的只是显示函数指针。

标签: c++ return factorial


【解决方案1】:
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;}
}

【讨论】:

  • 这个问题是在寻找一个解释,而不仅仅是为了工作代码。您的回答没有为提问者提供任何见解,可能会被删除。请edit解释导致观察到的症状的原因。
【解决方案2】:
To use a for loop as follows: 
int f=1, i=1;
for(i=1,f=1;i<=n;i++)
{
   {f=f*i;}
}

【讨论】:

  • 这个问题是在寻找一个解释,而不仅仅是为了工作代码。您的回答没有为提问者提供任何见解,可能会被删除。请edit解释导致观察到的症状的原因。
【解决方案3】:

当你使用

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&lt;&lt;,而不是函数调用返回的值

在这种情况下,函数指针被转换为布尔值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()
{
   ...
}

【讨论】:

  • 啊,那是程序的错误。我进行了该函数调用,现在它工作正常。感谢您的帮助和清晰的解释。
猜你喜欢
  • 1970-01-01
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
相关资源
最近更新 更多