Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
+ 2

# Weird Code Issue

So I have a square root calculator in C++. It works great when I enter a number, gives accurate square roots, and so on. But when I don't enter a number into it, it says this: The square root of 2686816 is 1639.15 Why does it do this and how can I stop it? I don't know if this is relevant, but I am using #include <cmath> for my square roots. This is the full code: #include <iostream> #include <cmath> using namespace std; int main() { //Initializes 'user_input' int user_input; //Defines 'user_input' cin >> user_input; //Prints the square root of the user's input cout << "The square root of "; cout << user_input; cout << " is "; cout << sqrt(user_input) << endl; cout << "Thank you for viewing my project!" << endl; int Haha; Haha = sqrt(5*5*5*5) ; if (user_input == Haha) { cout << "Hey, your number," << user_input << ", is my alpha number!" ; } return 0; }

9th Dec 2017, 9:07 PM
The Most Awesomest Peson
11 Réponses
+ 12
10th Dec 2017, 7:33 AM
🎀Cyber Joy🎀
+ 4
If you want to prove to yourself that the value comes in with garbage already, put this immediately after "int user_input;" cout << user_input; You'll see the preloaded garbage value.
9th Dec 2017, 10:59 PM
Kirk Schafer
+ 3
Do a cout of a value before you calculate the sqrt. That will give you an idea of whats happening
9th Dec 2017, 9:07 PM
Dextozz
+ 2
Put this in your code: user_input = 0; between initializing and cin. Now it gets some random value out of storage if you don't give a value for input..
9th Dec 2017, 10:08 PM
Paul
+ 2
Or change this line: int user_input; to: int user_input = 0;
9th Dec 2017, 10:16 PM
Paul
+ 2
it's because you didn't initialize the variable try initializing it. int var(0); or std::string =""; etc. another good habit is to give it valid initializing variables since here on sololearn people often hit enter not knowing what value to input. this lets them have a valid run their first time and keep interest long enough to learn what input to enter.
10th Dec 2017, 4:17 AM
Michael Simnitt
+ 1
Thanks all!
9th Dec 2017, 11:02 PM
The Most Awesomest Peson
0
OK I will try that @Dextozz
9th Dec 2017, 9:08 PM
The Most Awesomest Peson
0
Wait, How Do I do that? Do you mean tell it to output my input? When it says The square root of (number input) is (square root), 2686816 is the number that it says is input So if I enter 25 as the number, it says the square root of 25 is 5.
9th Dec 2017, 9:18 PM
The Most Awesomest Peson
0
Hmmm paste your code here. I don't know why that's happening. If you are inputing an int it should say the square root of 0 is 0
9th Dec 2017, 9:37 PM
Dextozz
0
Multiple people helped, and everything tried worked. Thanks!!
9th Dec 2017, 11:06 PM
The Most Awesomest Peson
Aujourd'hui en vedette
python