tags:

views:

174

answers:

7

Could anyone please tell me how to check what number I've got from a * b? Which is I would like to know every part of this number so for example if the result from this expression would be 25 I would like to know that first digit is two and second digit is five.

+2  A: 

You have to get the result of the integer division by the appropriate power of ten.

int exp = std::floor( std::log10( num ) );
int first_digit = num / int( std::pow( 10.0, exp ) );

This is an (inefficient) way to get the first digit directly. It would be better to iterate starting from the last.

UncleZeiv
@UncleZeiv yes that would solve the problem with the unit part but how to get tens and hundreds and so on? I thought maybe some bit shifting would be of help.
There is nothing we can do
+2  A: 
int val = res;

while( val > 0 )
{
   std::cout << val % 10 << endl; 
   val /= 10;
}
Goz
+3  A: 
a mod 10 == last digit of a
a / 10 == a without its last digit

So, for 25:

25 % 10 == 5 => 5 is the last digit of 25
25 / 10 == 2
2 % 10 == 2 => 2 is the first digit of 25

You can use these in a while loop to get each digit.

while (num > 0)
{
    digit = num % 10;
    // digit is now the current digit, counting from the right towards the left.
    num /= 10;
}
IVlad
+6  A: 

perhaps a little overkill... but even works with doubles

#include <sstream>
#include <iostream>

int main()
{
    double a = 5.2;
    double b = 7;
    double z = a*b;

    std::stringstream s;
    s << z;

    for (int i = 0; i < s.str().length(); i++)
        std::cout << i << ": " << s.str()[i] << std::endl;

    return 0;
}
osti
simple but effective :)
UncleZeiv
There is going to be a `.` somewhere :)
Matthieu M.
+1  A: 
char str[30];
sprintf(str,"%d",a*b);
int ndigits = strlen(str);

There you have all digits of your value in the string, and the number of digits in ndigits.

e.g. if a*b = 25 you get

ndigits==2
str[ndigits-1]=='5'
str[ndigits-2]=='2'

What do you want this for?

Stéphane
@Stephane good idea +1
There is nothing we can do
A: 

Just remember, that e.g. 2101 is basically just 2*10^3 + 1*10^2 + 0*10^1 + 1*10^0.

InsertNickHere
Wrong. `1234 / 10^2` will give you `12`, not the digit at the second position
IVlad
Yeah, i saw that and im trying to fix it right now.
InsertNickHere
You were very close initially :). You can use `(num / 10^k) % 10` to get the `k` th digit.
IVlad
+1  A: 

There's probably an underlying misunderstanding here. The result of the multiplication will most likely be 0x00000019. (Number of leading zeroes will differ). The second step, converting it to canonical decimal will yield "25".

It's important to realize that computers, unlike normal humans, don't do their math in decimal but in binary. Hence, if you want to check a property like "last decimal digit of a number", it's not directly available to them.

MSalters