【发布时间】: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。我建议阅读如何调用函数。您所做的只是显示函数指针。