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
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
+ 1
What if b = -100?
+ 1
Thank you so much 💓💓
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