【发布时间】:2020-03-17 11:12:00
【问题描述】:
我正在制作一个 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;
}
我知道一定有更好的方法。请帮忙。通过谷歌浏览但不了解那里的复杂程序,因为我还是一个初学者。
提前致谢。
【问题讨论】:
-
这不是真正的编程问题,而是数学问题。有几种(高效和低效)算法。首先你应该选择一个并深入研究它,直到你详细理解它,然后尝试实现它。
-
首先,您需要知道未初始化的局部变量(如您的
squarertoot变量)具有 indeterminate 值,使用它们会导致 undefined行为。其次,您将squareroot声明为 整数 变量,您不能添加浮点值并期望它正常工作。 -
对不起,我弄错了,刚刚编辑了 squareroot = 1;
标签: c++