Hey guys! I'm trying to make a basic program that will find square roots via a "check every number" method. The code works perfectly and will return correct answers when the answers are whole numbers as well as the entered number, but when I change the code to work with "0.01", or any other decimal, instead of "1" it always returns a rounded down version of the answer, i.e. when I input "9" it returns "2" and when I enter "321" I get "17 while the correct answer would be "17.9". It still kind of works, but I would prefer precision. Here's the code. Any help would be appreciated.

#include <iostream>

using namespace std;

int sqrt(int x){

float n=0.01; //These are the numbers I switch between 1 and 0.01

float k;

while (true) {

k = n*n;

if(k == x){

cout<< "if \n";

return n;

break;

}

else if (k<x){

cout<< "else if 1 \n";

n = n + 0.01; //These are the numbers I switch between 1 and 0.01

}

else if (k>x){

cout<< "else if 2 \n";

n = n - 0.01; //These are the numbers I switch between 1 and 0.01

return n;

break;

}

else{

cout<< "else \n";

break;

}

}

}

int main()

{

float x;

cin>> x;

cout<<sqrt(x);

cin.ignore();

cin.get();

}

#include <iostream>

using namespace std;

int sqrt(int x){

float n=0.01; //These are the numbers I switch between 1 and 0.01

float k;

while (true) {

k = n*n;

if(k == x){

cout<< "if \n";

return n;

break;

}

else if (k<x){

cout<< "else if 1 \n";

n = n + 0.01; //These are the numbers I switch between 1 and 0.01

}

else if (k>x){

cout<< "else if 2 \n";

n = n - 0.01; //These are the numbers I switch between 1 and 0.01

return n;

break;

}

else{

cout<< "else \n";

break;

}

}

}

int main()

{

float x;

cin>> x;

cout<<sqrt(x);

cin.ignore();

cin.get();

}

Probably because the return type of the sqrt-function is int, is my initial guess.

Last edited on

*Blush* O.O oh... umm... *nervous chuckle*

That solved my problem :P

Like I said, I'm a beginner. Thanks

That solved my problem :P

Like I said, I'm a beginner. Thanks

Topic archived. No new replies allowed.