Issue with assignment to a variable

// Example program
#include <iostream>
using namespace std;
int main()
{
cout<<"Please enter number";
double num;
cin>>num;
num==3*num;
cout<<num;
}

In the above code, I expected output num to be assigned 3 times the input, which is not the case. Instead, I find output the same as input. Although I get output as 3 times the input with the following code, my query is why the first program did not work.


1
2
3
4
5
6
7
8
9
10
11
  // Example program
#include <iostream>
using namespace std;
int main()
{
  cout<<"Please enter number";
  double num;
  cin>>num;
  cout<<3*num;
}
Last edited on
Not psychic. What issue?
closed account (E0p9LyTq)
why the first program did not work.

It didn't work because of this line of code: num==3*num;

You are comparing num to 3 * num, not assigning.

Try either num = 3 * num; or num *= 3;
This num == 3*num; performs an equality comparison with == (and discards its result).

This is what you intended: num = 3*num ; (= is assignment)
Thanks!
Topic archived. No new replies allowed.