qfedu-basic-level/day7/homework/h18.cpp

30 lines
580 B
C++
Raw Permalink Normal View History

2023-06-21 11:31:26 +08:00
// 输入一个数,输出它的平方根
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "请输入一个整数: ";
cin >> x;
int left = 0, right = x;
int mid;
while (left <= right)
{
int mid = (left + right) / 2;
if (mid * mid == x)
{
cout << x << " 的平方根为: " << mid << endl;
return 0;
}
else if (mid * mid < x)
left = mid + 1;
else
right = mid - 1;
}
cout << x << " 找不到平方根" << endl;
return 0;
}