0

I have problem in writing an simple algorithm

I have to write an algorithm which takes two number and compare which have more digits It's an basic C++ course question please help me <3

1st Nov 2021, 12:03 AM
Armin Abd
4 ответов
+ 2
If the numbers are integers then you could compare their magnitudes. Magnitude can be calculated. It is the integer portion from a number's logarithm, base 10. The logarithm function does not work for zero or negative numbers, so the code below accounts for those conditions. #import <math.h> magnitude = (num ? trunc(log10(abs(num))) : 0); Technically, the number of digits is magnitude+1, but adding 1 is unnecessary in order to compare two numbers. Here is a related program that shows number of digits. https://code.sololearn.com/cGN8zCE1fPxa/?ref=app
1st Nov 2021, 2:34 AM
Brian
Brian - avatar
+ 1
What if b = -100?
1st Nov 2021, 1:33 AM
Flash
+ 1
Thank you so much 💓💓
1st Nov 2021, 4:34 AM
Armin Abd
0
I'll tell you a way which is probably the most simple way to do this. Just compare the two numbers, the one with higher number is digits will have the higher value. For example, #include <iostream> #include <cstdlib> int a=99; int b=100; if(std::abs(a)>std::abs(b)) { std::cout<<"a has more digits"; } else { std::cout<<"b has more digits"; } Or you can convert the number to a string and compare the lengths of the two strings Edit:Thx to Flash for mentioning my mistake
1st Nov 2021, 1:21 AM
Rishi
Rishi - avatar