我的c ++程序在代码块中提供了正确的结果,但在visual basic 2005 express edition中给出了错误的结果

时间:2017-03-04 06:37:56

标签: c++

我的c ++程序在代码块中提供了正确的结果,但在visual basic 2005 express edition中给出了错误的结果。任何人都可以指导我做错了什么:)谢谢:) 这是我使用函数查找阶乘的程序。

#include <iostream>
using namespace std;

int fact( int a)
{
    if (a>1)
    return a*fact(a-1);
}
int  main()
{
    cout<<"Enter a number to find its factorial : ";
    int a;
    cin>>a;
    cout<<"Factorial of "<<a<<" is "<<fact(a)<<endl<<endl;
}

导致代码块

Enter a number to find its factorial : 5
Factorial of 5 is 120

Visual Basic 2005 express edition的结果

Enter a number to find its factorial : 5
Factorial of 5 is -96

1 个答案:

答案 0 :(得分:1)

您的代码行为未定义。

如果a <= 1函数中的fact,则无法返回值。未能返回值会导致未定义的行为,从而导致您看到不同的结果。

更正应该是:

int fact( int a)
{
    if (a>1)
       return a*fact(a-1);
    return 1; 
}