2015-05-27 67 views
-1

[编辑] - 没关系,这是一个非常愚蠢的问题不进入while循环?

我目前正在试图建立一个程序,将基本上告诉我,当插入排序的时间比给abn合并排序的时间较长(在这种情况下,2)的连续幂。这是我到目前为止有:

int comparisonSort() 
{ 

//prompt user for values of a and b 
int a = 0; 
int b = 0; 
cout << "Enter the value for a" << endl; 
cin >> a; 
cout << "Enter a value for b" << endl; 
cin >> b; 

double insertionSortTime = 0; 
double mergeSortTime = 0; 
double n = 2; 

cout << outside while loop" << endl;    //check 

while (insertionSortTime < mergeSortTime) 
{ 
    cout << "inside while loop" << endl;   //check 

    //compute the insertion and merge sort execution times 
    insertionSortTime = a*n*n; 
    mergeSortTime = b*n*log2(n); 

    cout << "is = " << insertionSortTime << " ms = " << mergeSortTime << endl; 

    n = pow(n, 2); // n^2 
} 

cout << "value of n that insertion sort beat merge sort is: " << n << endl; 
return 0; 
} 

,当我跑,我得到:

Enter the value for a 
8 
Enter a value for b 
64 
outside while loop 
value of n that insertion sort beat merge sort is: 2 

我不知道为什么没有得到执行while循环...如果这似乎对不起像一个非常简单的问题,但我是新来的C++和任何帮助将不胜感激,谢谢!

回答

3

该条件在

while (insertionSortTime < mergeSortTime) 

是在第一次迭代false当两个insertionSortTimemergeSortTime被设置为零。这就解释了为什么循环从未被执行。

也许你想用的:

while (insertionSortTime <= mergeSortTime) 
+1

我刚才十秒钟才意识到谢谢!我会接受你的答案,但我必须再等10分钟。 – ocean800

3

它,因为你有insertionSortTime = 0mergeSortTime = 0并为您的循环条件为insertionSortTime < mergeSortTime

当然0不是< 0所以它永远不会进入循环。

将其更改为<=