Ternary Operator
Hi guys!
I have this code, but I don't understand why it works...
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
using namespace std;
int main(){
int a = 1;
while (a <= 10){
cout << (a % 2 ? "****":"++++++++++")<< endl;
a++;
}
return 0;
}
| |
The output is this...
****
++++++++++
****
++++++++++
****
++++++++++
****
++++++++++
****
++++++++++
|
Why this
cout << (a % 2 ? "****":"++++++++++")<< endl;
is true when a = 1, ?
thanks.
It's to do with the nature of modulo/remainder'ing and of integer division.
To quote wikipedia:
When dividing 3 by 10, 3 is the remainder as we always take the front number as the remainder when the second number is of higher value. |
So your program, seeing 2 as the larger number in 1 / 2 is deciding 1 is the remainder.
Try:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
int main(){
int a = 1;
while (a <= 10) {
std::cout << "a = " << a << "\t"
<< a << " % 2 = " << a % 2
<< "\n"
<< ((a % 2) ? "****" : "++++")
<< "\n";
a++;
}
std::cout << std::flush;
return 0;
}
|
a = 1 1 % 2 = 1
++++
a = 2 2 % 2 = 0
****
a = 3 3 % 2 = 1
++++
a = 4 4 % 2 = 0
****
a = 5 5 % 2 = 1
++++
a = 6 6 % 2 = 0
****
a = 7 7 % 2 = 1
++++
a = 8 8 % 2 = 0
****
a = 9 9 % 2 = 1
++++
a = 10 10 % 2 = 0
**** | |
As for the others... well 3 / 2 == 1.5 . Integer division is truncating so you get 3 / 2 == 1. That leaves a remainder of 1.
Last edited on
Thanks!
Topic archived. No new replies allowed.