我正在编写一个C++程序来计算一个数字的平方根。这个程序不使用“sqrt”数学内置操作。有两个变量,一个是用户将要输入的数字,另一个是该数字的平方根。这个程序效果不是很好,我相信有更好的方法可以做到:
以下是我的完整代码:
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
我知道一定有更好的方法。请帮忙,我在谷歌上搜索过,但由于我还是初学者,不理解那里复杂的程序。提前感谢。
squareroot
为一个整数变量,你不能添加一个浮点数的值并期望它正常工作。 - Some programmer dude