Aug 28, 2009 at 2:26pm
Hi
I want to know how to get the first three digits of a four digit number in C++.Any suggestion?
Aug 28, 2009 at 3:01pm
Which first three digits?
Aug 28, 2009 at 5:08pm
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.
Aug 28, 2009 at 6:17pm
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 Aug 28, 2009 at 6:48pm
Aug 28, 2009 at 6:34pm
exp(n)
should just be e^n as I check it now
Aug 28, 2009 at 6:44pm
wat
1234/10*e^1 ~= 1234/27.183 ~= 45.4
1234/10^1 == 123 (integral division)
Aug 28, 2009 at 10:19pm
Gregor:
I didn't know the modulus operator in C++. :S
As stated by helios, mine work too.
Aug 29, 2009 at 3:01am
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 Aug 29, 2009 at 3:05am
Aug 29, 2009 at 3:10am
@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 Aug 29, 2009 at 3:07pm
Aug 29, 2009 at 3:06pm
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 Aug 29, 2009 at 3:28pm
Aug 29, 2009 at 3:13pm
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 Aug 29, 2009 at 3:13pm
Aug 29, 2009 at 3:23pm
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 Aug 29, 2009 at 3:40pm
Aug 29, 2009 at 3:43pm
so the remainder is 34...
Aug 30, 2009 at 3:25am
@Alan, it shows 34 here...