2)Why the program doesnt ask for me to cin the getline part? It only asks me to input x and then outputs "enter word" and thats it.... not sure whats the error but when i remove lines from int x; to cin>> x; . It works fine and would ask me to input my string.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int x;
cout<< "enter x :";
cin >> x;
1) 11 / 100 is an int / int which means that the result is an int (0). So 0 is then multipled by 50 to give 0. To give a float result for division, at least one of the numbers needs to be of type float
x = 11.0 / 100 * a;
2) stream extraction (cin) extracts up to a white-space char but doesn't extract that char. getline() extracts until a \n is found (or other terminating delim) and does extract and discard the delim. Hence the delim terminating the cin >> is the first char obtained for getline() which is a '\n' which terminates the getline!
This is a common issue when mixing >> and getline().
> 1) Why is my output 0 ? shouldnt it be 11 divided by 100 multipied by 50 = 5.5?
11/100 is done in integer arithmetic, which will round down to 0.
This zero is then promoted to double, multiplied by a, leaving you with zero.
Write 11.0 / 100 * a to force the compiler to promote the division to double.
> 2)Why the program doesnt ask for me to cin the getline part?
It does.
The problem is mixing >> and getline is a trap.
You see, >> will leave the \n on the input stream, which getline immediately sees before you type anything.
Hello. In our mind, when we divide an integer by an integer, we can get a floating number and all seems logical. For example, if I divide 3 by 2, I know that 1.5 is the result. However, for a computing system, if you divide an integer by an integer, you will get ... an integer - no more. In my previous example, you get 1. For this reason, you have to cast the values ++
Actually, you don't need to explicitly cast any of the values. You could just reorder as x= 11*a/100;
since a is a double.
Personally I'd just write x= 0.11*a;
However, for a computing system, if you divide an integer by an integer, you will get ... an integer - no more.
Well, that's true in C++/C and many languages and has been well and truly identified as the fault here. However, don't take it as gospel in all languages - in particular, it isn't true in Python, for example.
However, for a computing system, if you divide an integer by an integer, you will get ... an integer - no more.
Well, that's true in C++/C and many languages and has been well and truly identified as the fault here. However, don't take it as gospel in all languages - in particular, it isn't true in Python, for example.
Yes. I guess that many other languages compute numbers (including integers) in a different way.
Your comment is relevant and deserves to be noted. Well done ++