qfedu-basic-level/day9/homework/h8.cpp

37 lines
728 B
C++

// 编写一个函数,用于计算一个整数的平方根,并返回结果。
#include <iostream>
using namespace std;
int squareRoot(int x)
{
int left = 0, right = x;
int mid;
while (left <= right)
{
mid = (left + right) / 2;
if (mid * mid == x)
return mid;
else if (mid * mid < x)
left = mid + 1;
else
right = mid - 1;
}
return -1; // 找不到平方根
}
int main()
{
int x;
cout << "请输入一个整数: ";
cin >> x;
int result = squareRoot(x);
if (result == -1)
cout << x << " 找不到平方根" << endl;
else
cout << x << " 的平方根为: " << result << endl;
return 0;
}