Question:
How do you create a C++ loop to get this result without the use of arrays or strings?
google
2017-10-28 07:28:25 UTC
Lets say you have a number 57428 ,and you have another number 69483 which is equal in length how do you
get this result?
5*6 + 7*9 + 4*4 + 2*8 + 8*3
The individual digits of each number are multiplied and added together.
I'm guessing it could be a nested for loop that loops through both numbers digits and a variable to store the total
Four answers:
?
2017-10-28 16:36:38 UTC
int num1,num2,res=0;

num1= 57428;

num2= 69483 ;



while(num1){

res+=((num1%10) *(num2%10));

num1/=10;

num2/=10;

}

printf("%d\n",res);
husoski
2017-10-28 11:15:07 UTC
That's almost right, but % is a division operator with the same precedence as * and /. So, you need parentheses:



total += testnum%10 * (testnum2 %10);



I'd put both remainders in parens just for symmetry:



total += (testnum % 10) * (testnum2 % 10);
oldprof
2017-10-28 08:09:42 UTC
That's called an inner or dot product. And in fact you're right, you need to use and inner loop and outer loop (nested) as you parse each digit in both numbers.



But I'm guessing (because the last time I coded C++ was two decades ago) that there is a preprogrammed C++ function that can do inner products. Unfortunately I've long since thrown my C++ primer away, so I can't look it up. Have you tried the web?



Hey! I just did the search and here it is:



http://www.cplusplus.com/reference/numeric/inner_product/
google
2017-10-28 07:36:57 UTC
int testnum = 5031;

int testnum2 = 5425;

int total = 0;



while (testnum >0 && testnum2 > 0){

cout << testnum << endl << testnum2 << endl;

total+=testnum%10 * testnum2%10 ;

testnum/=10;

testnum2/=10;



Tried this but last loop results in total being 16 instead of 36


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...