我的C++程序在代码块中给出了正确的结果,但在visual basic 2005 express版本中给出了不正确的结果
我的C++程序在代码块中给出了正确的结果,但在visual basic 2005 express edition中给出了不正确的结果。任何人都可以请指导我做什么我做错了:)谢谢:) 这里是我的程序找到使用函数的阶乘。我的C++程序在代码块中给出了正确的结果,但在visual basic 2005 express版本中给出了不正确的结果
#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
代码的行为是不确定的。
如果a <= 1
在fact
函数中,则无法返回值。未能返回值会导致未定义的行为,因此会看到不同的结果。
修正应该是:
int fact(int a)
{
if (a>1)
return a*fact(a-1);
return 1;
}
谢谢PaulMcKenzie :)现在它在vb 2005中工作正常:) – Romeo
你可能还没有看到这个问题。使用的编译器无关紧要 - 行为或原始程序未定义。未定义意味着任何答案都可能已经被显示,程序可能已经崩溃,并且是的,甚至可能已经打印了“正确的”答案。防止这种情况的方法是编写代码,以便行为定义良好。 – PaulMcKenzie
确定:)谢谢:) – Romeo
你什么回报,如果一个' PaulMcKenzie
在codeblocks,使一个 Romeo
请阅读我的答案。问题是你没有从应该返回一个值的函数返回一个值。无论函数做什么,这都是未定义的行为。 – PaulMcKenzie