-2

Hellou guys, I am a beginner with self learner of C++. today I tried to make a simple calculator but the debugger keeps on showing me the same error on and on. Unitianalized variable used "X" ; Unitianalized variable used "Z"

Here is the code :

#include <iostream>
using namespace std;

int main()
{
    float x, z, a;
    a = x + z;



    cout << "Welcome to the calculator" << endl;
    cout << "State the first number " << endl;
    cin >> x ;
    cout << "State the second number " << endl;
    cin >>  z ;
    cout << "If you wanted to time number" << x << "by this number" << z << "The result would be : " << a << endl;



    system("pause");
    return 0;
} 
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • Possible duplicate of [warning: uninitialized variable //But I have initialized ! C++ Compiler bug?](https://stackoverflow.com/questions/6813660/warning-uninitialized-variable-but-i-have-initialized-c-compiler-bug) – A Jar of Clay Mar 07 '19 at 11:39
  • 2
    Please don't update a question with "improvements"; it makes the answers nonsense. (I've rolled it back.) Accept an answer that helps, and if you have any further problems, post another question. (And you should get yourself a book from [this list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read about "assignment".) – molbdnilo Mar 07 '19 at 12:06
  • 1
    sometimes less is more, "Hellou guys" kind of excludes roughly half of the community for no good reason ;) – 463035818_is_not_an_ai Mar 07 '19 at 12:18
  • 1
    adding to molbdnilos comment: If you want to share your fixed/improved code, it is perfectly fine to answer your own question, but you really should not fix the code in the question itself – 463035818_is_not_an_ai Mar 07 '19 at 12:19

2 Answers2

0

You should initialize your variables and calculate a after you read x and z. Take a look at this: https://www.learncpp.com/cpp-programming/eight-c-programming-mistakes-the-compiler-wont-catch/

#include <iostream>
using namespace std;

int main()
{
    float x = 0.0f, z = 0.0f, a = 0.0f;

    cout << "Welcome to the calculator" << endl;
    cout << "State the first number " << endl;
    cin >> x ;
    cout << "State the second number " << endl;
    cin >>  z ;
    a = x + z;
    cout << "If you wanted to time number" << x << "by this number" << z << "The result would be : " << a << endl;



    system("pause");
    return 0;
} 
julians
  • 71
  • 5
0

The order in which you do things matters.

int x = 5, z = 2;

int a = x + z; // a is 7

z = 5; // a is still 7

a = x + z; // now a is updated to 10

So in your code when you do a = x + z; both x and z are uninitialized. It's undefined behavior to use uninitialized variables.

To fix it, move the a = x + z; to after you have input values to x and z.

super
  • 12,335
  • 2
  • 19
  • 29