Hi
I want to know how to get the first three digits of a four digit number in C++.Any suggestion?
Which first three digits?
If the number is 1234 and you want 123, then:
int value = 1234;
int newVal = value / 10;
If you instead want 234, then:
int value = 1234;
int newVal = value - value / 1000 * 1000;
At this point newVal can be printed or whatever.
webjose what are you doing for 234, makes no sense
for 234:
int newVal = value%1000;
general:
get rid of last n digits in number a
a/10^n
get rid of first n digits in number a
a%10^n
Last edited on
exp(n)
should just be e^n as I check it now
wat
1234/10*e^1 ~= 1234/27.183 ~= 45.4
1234/10^1 == 123 (integral division)
Gregor:
I didn't know the modulus operator in C++. :S
As stated by helios, mine work too.
truncation:
1 2 3 4 5
|
stringstream ss;
short number = 1234;
ss<< number;
short firstThreeNumbers = atoi(ss.str().substr(0, 3).c_str());
cout << firstThreeNumbers << '\n';
| |
division of integer:
1 2 3
|
short number = 1234;
short firstThreeNumbers = number/10; // truncates remainder... floor()
cout << firstThreeNumbers << '\n';
| |
Last edited on
@Gregor
get rid of first n digits in number a
a%10^n |
I thought that a modulus returns:
could you walk me through that
Last edited on
In computing, the modulo operation finds the remainder of division of one number by another. |
Why is is in C++ either 0 or 1 is returned?
1 2 3 4 5 6
|
int n1 = 5;
int n2 = 4;
int imod1 = n1 % 2;
int imod2 = n2 % 2;
cout << imod1 << '\n'; // 1
cout << imod2 << '\n'; // 0
| |
Last edited on
1 2
|
double dmod1 = (double)(n1 % 2);
double dmod2 = (double)(n2 % 2);
| |
|
You are mod-ing two integers THEN casting them to double.
Last edited on
well, thats wrong but so is this...
a%10^n
say
1 2 3
|
1234%102 ->
1234%100 ->
?????????
| |
the remainder is 12.34, but in c++ this would = 1...
Last edited on
so the remainder is 34...
@Alan, it shows 34 here...