没有进入while循环

Not entering while loop?

本文关键字:while 循环      更新时间:2023-10-16

[EDIT] -没关系,这是一个非常愚蠢的问题

我目前正在尝试创建一个程序,它基本上会告诉我,对于给定的a, bn(在这种情况下,连续的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++和任何帮助将非常感激,谢谢!!

中的条件
while (insertionSortTime < mergeSortTime)
insertionSortTimemergeSortTime均为零时,第一次迭代

false。这就解释了为什么循环永远不会被执行。

也许你想用:

while (insertionSortTime <= mergeSortTime)

这是因为你有insertionSortTime = 0mergeSortTime = 0,而循环的条件是insertionSortTime < mergeSortTime

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

更改为<=