I am making a calculator in c++ and I have everyting done except factorial which has one issue: my int number is "uninitialized" this is a console application on vscommunity2019 on windows10 if that helps. Everything works perfect except factorial,when I test it theonly error is the int number.
#include <iostream>
using namespace std;
int main()
{
float n1;
char op;
float n2;
int co;
int i;
int fact = 1;
int number;
calculations: std::cout << "Enter n1!";
std::cin >> n1;
std::cout << "\nEnter operator! Here are your choices: + - * / !";
std::cin >> op;
std::cout << "\nEnter n2!";
std::cin >> n2;
switch (op)
{
case '+':
std::cout << n1 + n2;
break;
case '-':
std::cout << n1 - n2;
break;
case '*':
std::cout << n1 * n2;
break;
case '/':
std::cout << n1 / n2;
break;
case '!':
for (i = 1; i <= number; i++) {
fact = fact * i;
}
std::cout << number;
break;
default:
std::cout << "Error! operator is not correct";
break;
}
std::cout << "\nWant to continue?Y(type 1)/N(type 0)";
std::cin >> co;
if (co == 1) {
goto calculations;
}
return 0;
}
Well, number
is uninitialized.
int main()
{
int number; //uninitialized local variable
[...] //no usage of number
case '!':
for (i = 1; i <= number; i++) { //first usage of number, before initializing it!
fact = fact * i;
}
std::cout << number;
break;
[...]
}
Luckily you get a compilation error and can fix it (thanks MSVC!). For gcc (when trying in compile explorer, it compiles, but I assume there will be a runtime error).
Solution? Probably replace number
with n1
in the loop, and output fact
.