2009-06-23 100 views
0

此程序需要從用戶輸入2號,詢問他們是否想找出排列或組合,並且然後輸出該結果。這是代碼。排列組合 - 運行時失敗

#include "std_lib_facilities.h" 

int permutation(int first, int second) 
{ 
int top_fac; 
int bottom_fac; 
for (int i = first-1; i >= 1; --i) 
    top_fac *=i; 
for (int i2 = (first-second)-1; i2>=1; --i2) 
    bottom_fac *= i2; 
return (top_fac/bottom_fac); 
} 

int combination(int first, int second) 
{ 
int bottom_fac; 
for (int i = second-1; i>=1; --i) 
    bottom_fac *= i; 
return permutation(first, second)/(bottom_fac); 
} 

int main() 
{ 
cout << "Enter two numbers.\n"; 
int first = 0; 
int second = 0; 
cin >> first >> second; 
cout << "Now choose permutation(p) or combination(c).\n"; 
string choice; 
cin >> choice; 
if (choice == "p") 
    cout << "Number of permutations: " << permutation(first,second) << endl; 
else if (choice == "c") 
    cout << "Number of combinations: " << combination(first,second) << endl; 
else 
    cout << "p or c stupid.\n"; 
keep_window_open("q"); 
} 

當我嘗試運行該程序,並選擇p或c時,出現「permutations_combinations.exe has stopped working」消息。我試圖發現一個錯誤,但沒有提到。有任何想法嗎?

在此先感謝。

+0

不知道爲什麼這被標記爲「家庭作業」。 – Alex 2009-06-30 04:00:05

回答

4

你不初始化局部變量top_facbottom_fac你的函數裏面。與其他語言不同,局部變量不會初始化爲C或C++中的任何內容。他們收到的值是當您調用函數時發生在堆棧上的任何垃圾。你應該明確地在的permutation()combination()功能開始初始化top_facbottom_fac爲1。

我在猜想bottom_fac意外地被初始化爲0,然後你在功能的末尾除以0,這會導致你看到的運行時失敗。

1

確保您初始化top_facbottom_fac

+0

Gah當然!非常感謝你。 – Alex 2009-06-23 02:23:21

+0

那麼,實際上必須首先將top_fac和bottom_fac初始化爲第一個和第二個,因爲它計算的是階乘。 – Alex 2009-06-23 02:26:30

0

未初始化的變量。

0

我猜你的輸入導致您的for循環無限循環中的一個。仔細檢查一下。

0

一個建議 - 學習如何使用調試器。即使您正在Linux上開發,您也可以使用IDE來幫助您逐步完成代碼 - http://monodevelop.com/(等等)。在函數頂部設置一個斷點會告訴你你的變量沒有被初始化。