C: Round signed integer to nearest multiple - c

This feels like a basic question but I couldn't find a definitive answer so far.
I would like to implement an efficient function round_to_nearest(int x, int multiple), that rounds a signed integer x to the nearest multiple of multiple, avoiding using floating point arithmetic if possible.
Example output:
round_to_nearest(14, 5);
15
round_to_nearest(16, 5);
15
round_to_nearest(23, 5);
25
round_to_nearest(22, 5);
20
round_to_nearest(-23, 5);
-25
round_to_nearest(-22, 5);
-20

In integer arithmetic, if n is positive, add m/2, else subtract m/2, then divide by m (truncating integer divide), then multiply by m:
int round_to_nearest( int n, int m )
{
return (( n + ((n < 0) ? -m : m) / 2) / m ) * m ;
}
int main()
{
int test[] = {16, 23, 22, -23, -22} ;
int m = 5 ;
for( int i = 0; i < sizeof(test) / sizeof(*test); i++ )
{
printf(" round_to_nearest( %d, %d ) = %d\n", test[i], m,
round_to_nearest( test[i], m ) ) ;
}
return 0;
}
Output of test:
round_to_nearest( 16, 5 ) = 15
round_to_nearest( 23, 5 ) = 25
round_to_nearest( 22, 5 ) = 20
round_to_nearest( -23, 5 ) = -25
round_to_nearest( -22, 5 ) = -20
One caveat is that m must be > 0 - which in this context makes sense, I would accept that as a precondition for correct operation; checking for it as a runtime error is probably unnecessary, but you might include an assert to protect against programmer semantic error:
assert( m > 0 ) ;
Standard library asserts are removed when NDEBUG is defined - normally when debug support is disabled.

For positive numbers:
add half of the multiple to x
then perform integer division, which drops the fractional part
then multiply by the multiple to get the final answer
For negative numbers, the first step is a subtraction, instead of addition.
int round_to_nearest(int x, int multiple)
{
if (x >= 0)
return ((x + multiple / 2) / multiple) * multiple;
else
return ((x - multiple / 2) / multiple) * multiple;
}

In order to round to the next multiple in the direction of zero (i.e. down for positive numbers and up for negative numbers), all you have to do is to divide by that multiple and then multiply the result with the multiple. The rounding towards zero will be accomplished by the truncation in the division.
int round_toward_zero( int num, int multiple )
{
int quotient;
quotient = num / multiple;
return quotient * multiple;
}
However, since you stated that you wanted to round to the nearest multiple instead of the next multiple in the direction of zero, we must do the same thing, but we must add a small correction in cases in which we want to round in the other direction:
For positive numbers, if the remainder of the division is at least half of the multiple, then we must add 1 to the quotient before multiplying with the multiple, so that it is rounded away from zero.
For negative numbers, if the remainder of the devision is not more than half of the multiple we must add -1 to the quotient before multiplying with the multiple, so that it is rounded away from zero.
Therefore, in the following code, the variable correction can have the value -1, 0 or +1. For positive numbers, it will be either 0 or +1, and for negative numbers, it will be either -1 or 0.
#include <stdio.h>
int round_to_nearest( int num, int multiple )
{
int quotient, remainder, correction;
quotient = num / multiple;
remainder = num % multiple;
correction = remainder / ( (multiple + 1 ) / 2 );
return (quotient + correction) * multiple;
}
int main( void )
{
printf( "%d\n", round_to_nearest(14, 5) );
printf( "%d\n", round_to_nearest(16, 5) );
printf( "%d\n", round_to_nearest(23, 5) );
printf( "%d\n", round_to_nearest(22, 5) );
printf( "%d\n", round_to_nearest(-23, 5) );
printf( "%d\n", round_to_nearest(-22, 5) );
}
Output:
15
15
25
20
-25
-20

Integer division truncates towards zero; which is 0.5 smaller (in magnitude, on average) than a rounded to nearest result.
If you add the magnitude of 0.5 * divisor to the magnitude of the numerator, then the result will be 0.5 larger.
In other words, for unsigned integers:
result = (numerator + divisor/2) / divisor;
..or alternatively (with less rounding error when the divisor is odd, and higher risk of overflow - e.g. if numerator is INT_MAX):
result = (numerator*2 + divisor) / (divisor * 2);
For signed integers "magnitude" isn't "value"; and it becomes a mess when the numerator and divisor have a different sign. To fix that:
if( (numerator < 0) && (divisor < 0) ||
(numerator >= 0) && (divisor |= 0) ) {
/* Numerator and divisor have same sign */
result = (numerator*2 + divisor) / (divisor * 2);
} else {
/* Numerator and divisor have different sign */
result = (numerator*2 - divisor) / (divisor * 2);
}
To round to the nearest multiple, you just multiply by the divisor after the "round to nearest". The code becomes:
if( (numerator < 0) && (multiple < 0) ||
(numerator >= 0) && (multiple |= 0) ) {
/* Numerator and multiple have same sign */
result = (numerator*2 + multiple) / (multiple * 2);
} else {
/* Numerator and multiple have different sign */
result = (numerator*2 - multiple) / (multiple * 2);
}
result *= multiple;

Related

Write a program, which reads an Integer. Output another integer where the even digits are retained and odd digits are decremented by 1,

Here is my code:
#include <stdio.h>
#include <math.h>
int main() {
int num, i = 0, new_num = 0, u;
printf("Enter a number: ");
scanf("%d", &num);
while (num > 0) {
u = num % 10;
if (u % 2 == 0)
u = u;
if (u % 2 == 1)
u = u - 1;
new_num = new_num + u * pow(10, i);
num = num / 10;
i++;
}
printf("The new number is: %d", new_num);
return 0;
}
Now, when I am doing this in gcc(VS Code), for 2-digit number everything is ok. But for digits more than three I am getting a error. Like Input=23145 Output=22043. But I was expecting output=22044.
Also, if I run the same code in DevC/C++, there is no error.
Can anyone help me out in this?
Your program produces the expected output on my system: 22044 for 23145, but this might depend on the implementation of the pow function.
The reason you get a different output is probably a side effect of a precision issue with the pow() function in your C library: if pow(x, y) is implemented as exp(y * log(x)), the result for integral values of x and y could be very close but inferior to the actual integral value, causing the conversion to int to produce the previous integer. Some C library authors make a special case of integral arguments to avoid this problem, but it is highly recommended to avoid floating point functions for integer arithmetics to prevent such tricky issues.
I would advise some more changes in your code:
test the return value of scanf().
remove the if (u % 2 == 0) u = u; part, it has no effect.
in any case, there should be an else clause to not use the result of the previous case when testing for odd digits.
do not use the floating point function pow(): just keep a multiplier variable and update it in the loop.
the program does not handle negative numbers.
Here is a modified version:
#include <stdio.h>
int main() {
int num, new_num = 0, pow10 = 1;
printf("Enter a number: ");
if (scanf("%d", &num) != 1)
return 1;
while (num != 0) {
int digit = num % 10;
/* decrement odd digits absolute value */
digit -= digit % 2;
new_num = new_num + digit * pow10;
pow10 = pow10 * 10;
num = num / 10;
}
printf("The new number is: %d\n", new_num);
return 0;
}
Note that digit -= digit % 2; will decrement positive odd digits and actually increment negative odd digits, which effectively always decrements the absolute value of odd digits. This way both positive values and negative values are handled correctly.
In my instance of Visual Studio Code, for an input 23145, I indeed find 22044 as an output.
I guess the divergence comes with the cast of pow(10,i). Pow function in C returns a double which is not what you really want here. I strongly advice to not use the pow function for integer arithmetic.
A solution could be :
uint16_t i = 0u;
uint16_t current_digit = 0u, decimal_digit = 1u;
uint16_t new_number = 0u;
uint16_t number = 23145u;
while(number > 0u) {
current_digit = number % 10;
if (current_digit % 2) {
current_digit = current_digit - 1;
}
new_number = new_number + current_digit * decimal_digit;
decimal_digit *= 10u;
number /= 10;
i++;
}
printf("The new number is: %d", new_number);
It seems that the problem is using the function pow that returns a double value.
If you are dealing with integers then it is better to avoid using functions that return doubles due to a possible truncation then a double is converted to an integer.
Also pay attention to that the user can enter a negative number. Your program allows to do that. In this case your program also will produce an incorrect result.
I would write the program the following way
#include <stdio.h>
int main( void )
{
while (1)
{
const int Base = 10;
int num;
printf( "Enter a number (0 - exit): " );
if (scanf( "%d", &num ) != 1 || num == 0) break;
int new_num = 0;
for (int tmp = num, multiplier = 1; tmp != 0; tmp /= Base)
{
int digit = tmp % Base;
if (digit % 2 != 0)
{
digit += ( digit < 0 ? 1 : -1 );
}
new_num = new_num + multiplier * digit;
multiplier *= Base;
}
printf( "The original number is %d and the new number is: %d\n",
num, new_num );
putchar( '\n' );
}
}
The program output is
Enter a number (0 - exit): -123456789
The original number is -123456789 and the new number is: -22446688
Enter a number (0 - exit): 123456789
The original number is 123456789 and the new number is: 22446688
Enter a number (0 - exit): 0
If even for negative digits to add -1 then you should substitute this if statement
if (digit % 2 != 0)
{
digit += ( digit < 0 ? 1 : -1 );
}
for this one
if (digit % 2 != 0)
{
digit = ( digit -1 ) % Base;
}
In this case the program output might look like
Enter a number (0 - exit): -123456789
The original number is -123456789 and the new number is: -224466880
Enter a number (0 - exit): 123456789
The original number is 123456789 and the new number is: 22446688
Enter a number (0 - exit): 0
That is in this case the new value for the negative value -123456789 will be -224466880.

Power of nth number (table) in C

I'm making program that prints their nth power for numbers from 1 to 20, using recursive and non-recursive function. I would like to give an option for user to enter real numbers. How to do that? Can it be done without pow function? Thank you for your help!
If you want to raise a number to a real exponent x
a^x
you can compute it as
e^(x ln a)
so you can write a function like
double mypow( double base, double exponent )
{
return exp( exponent * log( base ) )
}
If you want to get deep into the weeds and create your own implementations of exp and log, you can use the Taylor series
e^x = 1 + x + ((x^2)/2!) + ((x^3)/3!) ...
and
ln x = 2( u + (u^3)/3 + (u^5)/5 ... ), u = (x+1)/(x-1)
Personally, I would just use the pow function.
In making double keiski_pow(double num, double exponent) consider different code for certain conditions.
// exponent == 0, num != 0
return 1
// exponent == 0, num == 0
Domain error
// num > 0
return exp(log(num)*exponent)
// or more accurately
return exp2(log2(num)*exponent)
// num == 0, exponent < 0
Infinity
// num < 0, exponent is an integer > 0.
// Integer test for `double`: trunc(exponent) == exponent
t = keiski_pow(num, exponent/2)
return t*t*(exponent%2 ? num : 1)
// or
t = keiski_pow(fabs(num), exponent)
return t*exponent%2 ? -1 : 1)
// num < 0, exponent is an integer < 0
return 1.0/keiski_pow(num, -exponent)
// num < 0, exponent is not an integer
Domain error
I think this covers most cases. (NaN are another story)
Note: recursion() is very very slow for large exponent. Try recursion(1.0, 1e15).
A much faster recursive solution:
double recursion_alt(double num, double exponent) {
// Code only valid when exponent has a whole number value
assert(exponent = trunc(exponent));
if (exponent > 0.0) {
double exponent_mod2 = fmod(exponent, 2.0);
double exponent_div2 = (exponent - exponent_mod2)/2.0;
double t = recursion_alt(num, exponent_div2);
return t*t*(exponent_mod2 ? num : 1.0);
}
if (exponent < 0.0) {
return 1.0/recursion_alt(num, -exponent);
}
return 1.0;
}

Finding the last 10 digits of 2^n

So i'm supposed to find out the last 10 digits of 2^n(0<=n<=100) where n is the input. I found a method to handle large numbers but the program fails when n>64. Any leads on how to go about with this would be appreciated.
#include<stdio.h>
#include<math.h>
/* Iterative Function to calculate (x^y)%p in O(log y) */
int power(long long int x, long long int y, long long int p)
{
long long int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0) {
// If y is odd, multiply x with result
if (y & 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// C function to print last 10 digits of a^b
void printLastDigits(long long int a,long long int b)
{
long long int temp = pow(10,10);
// Calling modular exponentiation
temp = power(a, b, temp);
if (temp)
printf("%d",temp);
}
int main()
{
long long int n;
scanf("%d",&n);
printLastDigits(2,n);
return 0;
}
You don't need to worry about the 'high' bits, since multiplication by 2 left shifts them out of range of the lower part of the product you're interesting in. Just be sure you're using the unsigned long long type (of at least 64 bits) to hold integral types that are wide enough, e.g.,
#include <inttypes.h>
#include <stdio.h>
void low_digits (unsigned int n)
{
unsigned long long base = 2, modulus = 10000000000ULL;
for (unsigned int i = 1; i <= n; i++)
{
fprintf(stdout, "2^%u mod 10^10 = %llu\n", i, base);
base = (base * 2) % modulus;
}
}
You can test 2^1000 with a bignum calculator:
10715086071862673209484250490600018105614048117055336074437503883703\
51051124936122493198378815695858127594672917553146825187145285692314\
04359845775746985748039345677748242309854210746050623711418779541821\
53046474983581941267398767559165543946077062914571196477686542167660\
429831652624386837205668069376
while n = 1000 above yields: 5668069376
Others have noted, that this is a naive method, and modular exponentiation is far more efficient for sufficiently large values of (n). Unfortunately, this is going to require products that exceed the range of an unsigned 64-bit value, so unless you're prepared to implement [hi64][lo64] multi-precision mul / mod operations, it's probably beyond the scope of your task.
Fortunately, later versions of gcc and clang do provide an extended 128 bit integral type:
#include <inttypes.h>
#include <stdio.h>
void low_digits (unsigned int n)
{
unsigned long long base = 2, modulus = 10000000000ULL;
__extension__ unsigned __int128 u = 1, w = base;
while (n != 0)
{
if ((n & 0x1) != 0)
u = (u * w) % modulus; /* (mul-reduce) */
if ((n >>= 1) != 0)
w = (w * w) % modulus; /* (sqr-reduce) */
}
base = (unsigned long long) u;
fprintf(stdout, "2^%u mod 10^10 = %llu\n", n, base);
}
The following uses strings to perform the multiplication:
void lastdigits(char digits[11], int n)
{
int i, j, x, carry;
for (i=0; i<n;i++) {
for (j=9, carry=0; j>=0; j--) {
x= digits[j]-'0';
x *= 2;
x += carry;
if (x>9) {carry= 1; x -= 10;}
else carry= 0;
digits[j]= x+'0';
}
}
}
void test(void)
{
char digits[11];
strcpy(digits,"0000000001");
lastdigits(digits,10);
printf("%s\n",digits);
strcpy(digits,"0000000001");
lastdigits(digits,20);
printf("%s\n",digits);
strcpy(digits,"0000000001");
lastdigits(digits,100);
printf("%s\n",digits);
}
Output:
0000001024
0001048576
6703205376
Since the other answers you've received don't actually show what you're doing wrong:
x = (x * x) % p;
You're assuming that x * x still fits in long long int. But if x is 0x100000000 (4294967296, for 10 decimal digits) and long long int is 64 bits, then it will not fit.
Either:
You need a way to accurately multiply two arbitrary 10-digit numbers. The result may have 20 digits and may not fit in long long int or even unsigned long long int. This means you'd need to use some bigint library or implement something like that yourself.
Or:
You need to avoid multiplying multiple possibly-10-digit numbers.
The answer you've accepted opts for simple repeated multiplication by 2. This is sufficient for your problem now, but beware that this does significantly increase the complexity if you want to allow very large exponents.
Let's say you are finding the last digit of 2^n, you just need to consider last digit and ignore every other digit
1. 2*2 = 4
2. 4*2 = 8
3. 8*2 = 16 (ignore last-but-one digit i.e 1)
4. 6*2 = 12 (ignore last-but-one digit i.e 1)
5. 2*2 = 4
6. 4*2 = 8
7. 8*2 = 16 (ignore last-but-one digit i.e 1)
8. 6*2 = 12 (ignore last-but-one digit i.e 1)
9. 2*2 = 4
... n-1 iterations
To find the last 2 digits of 2^n, ignore all digits except last 2 digits.
1. 2*2 = 4
2. 4*2 = 8
3. 8*2 = 16
4. 16*2 = 32
5. 32*2 = 64
6. 64*2 = 128 (Consider last 2 digits)
7. 28*2 = 56
8. 56*2 = 112 (Consider last 2 digits)
9. 12*2 = 24
... n-1 iterations
Similarly, to find the last 10 digits of 2^n, consider just last 10 digits at each iteration and repeat it for n-1 iterations.
Note:
With this approach, the biggest number you'll get during the calculation can be of 11 digits ~ 10^11, while for a 64-bit machine the max value is ~ 2^64 = ~ 10^18

how to check if the / operator has no remainder in C?

I want to check if the / operator has no remainder or not:
int x = 0;
if (x = 16 / 4), if there is no remainder:
then x = x - 1;
if (x = 16 / 5), if remainder is not zero:
then x = x + 1;
How to check if there are remainder in C? and
How to implement it?
Frist, you need % remainder operator:
if (x = 16 % 4){
printf("remainder in X");
}
Note: it will not work with float/double, in that case you need to use fmod (double numer, double denom);.
Second, to implement it as you wish:
if (x = 16 / 4), if there is no remainder, x = x - 1;
If (x = 16 / 5), then x = x + 1;
Useing , comma operator, you can do it in single step as follows (read comments):
int main(){
int x = 0, // Quotient.
n = 16, // Numerator
d = 4; // Denominator
// Remainder is not saved
if(x = n / d, n % d) // == x = n / d; if(n % d)
printf("Remainder not zero, x + 1 = %d", (x + 1));
else
printf("Remainder is zero, x - 1 = %d", (x - 1));
return 1;
}
Check working codes #codepade: first, second, third.
Notice in if-condition I am using Comma Operator: ,, to understand , operator read: comma operator with an example.
If you want to find the remainder of an integer division then you can use the modulus(%):
if( 16 % 4 == 0 )
{
x = x - 1 ;
}
else
{
x = x +1 ;
}
use the % operator to find the remainder of a division
if (number % divisor == 0)
{
//code for perfect divisor
}
else
{
//the number doesn't divide perfectly by divisor
}
use modulous operator for this purpose.
if(x%y == 0) then there is no remainder.
In division operation, if the result is floating point, then only integer part will be returned and decimal part will be discarded.
you can use Modulous operator which deals with remainder.
The modulus operator (represented by the % symbol in C) computes the remainder. So:
x = 16 % 4;
x will be 0.
X = 16 % 5;
x will be 1

Convert Decimal number into Fraction

I am trying to convert decimal number into its fraction. Decimal numbers will be having a maximum 4 digits after the decimal place.
example:- 12.34 = 1234/100
12.3456 = 123456/10000
my code :-
#include <stdio.h>
int main(void) {
double a=12.34;
int c=10000;
double b=(a-floor(a))*c;
int d=(int)floor(a)*c+(int)b;
while(1) {
if(d%10==0) {
d=d/10;
c=c/10;
}
else break;
}
printf("%d/%d",d,c);
return 0;
}
but I am not getting correct output, Decimal numbers will be of double precision only.Please guide me what I should do.
If your floating point number is x, then the numerator of the fraction over 10000 will be the integral part of (x + 0.00005) * 10000. It's up to you whether you want to reduce the fraction to simplest terms (i.e. divide out by the gcd of the numerator and denominator).
#include <stdio.h>
int main(void) {
double a = 12.34;
int c = 10000;
double b = (a - floor(a)) * c;
int d = (int)floor(a) * c + (int)(b + .5f);
printf("%f %d\n", b, d);
while(1) {
if(d % 10 == 0) {
d = d / 10;
c = c / 10;
}
else break;
}
printf("%d/%d\n", d, c);
return 0;
}
The problem is that b was getting 3400.00 but when you do (int) b you are getting 3399, so you need to add 0.5 so the number can truncate to 3400.
Getting 3400.00 is different than having 3400, 3400.00 means that the number was round to 3400, that's why when you do (int) 3400.00 it assumes that the nearest integer (less than the number you are converting) is 3399, however, when you add 0.5 to that number the last the nearest integer is now 3400.
If you want to acquire a deeper understanding of floating point arithmetic read What Every Computer Scientist Should Know About Floating-Point Arithmetic
My solution is quite simple, "lazy", runs by iteration, nothing fancy.
In most languages that have a decent Math library, you'll need nothing more than the algo itself.
But in bc, you'll need to implement simple functions such as
int() to return integer part of a number ,
abs() to return absolute value ,
float() to return floating part of a number ,
round() to round to nearest integer.
If nothing is found after (1/eps) iterations, the loop breaks with the last result.
eps=10^-4 /*Tweak for more or less accuracy */
define int(x) {
auto s ;
s = scale ;
scale = 0 ;
x /= 1 ;
scale = s ;
return x ;
}
define round(x) { return int(x+.5-(x<0)) ; }
define abs(x) { if ( x < 0 ) x=-x ; return x ; }
define float(x) { return abs(x-int(x)) ; }
define void frac(x) {
auto f, j, n, z ;
f = float(x) ;
j = 1 / eps ;
z = .5 ;
if ( f != 0 ) {
while ( ( n++ < j ) && ( abs( z - round(z) ) > eps ) ) z = n / f ;
n -= 1 ;
if ( x < 0 ) n = -n ;
x = int(x)
z = round(z) ;
print n + x*z , "/" , z , " = "
if ( x != 0 ) print x , " + " , n , "/" , z , " = "
}
print x+n/z , "\n" ;
}
With standard accuracy (eps=.0001), you can get this :
frac(-.714285)
-5/7 = -.71428571428571428571
sqrt(2)
1.414213562373
frac(sqrt(2))
19601/13860 = 1 + 5741/13860 = 1.414213564213
6-7/pi
3.77183080
eps=.000001 ; frac(6-7/pi)
1314434/348487 = 3 + 268973/348487 = 3.77183080
Here is the algorithm that I use. It's an iterative process that works as follows:
The initial approximation for the numerator is 1 and the denominator is 1 divided by the fraction portion of the floating point value. For example, when converting 0.06 to a fraction, the denominator = 1/0.06 = 16.66666667 (rounded to 17), thus the initial approximation is 1/17.
The difference between the floating point value and the the current approximation is computed. For the example, the difference is 1/17 - 0.06 = 0.058824 - 0.06 = -0.001176.
If the absolute value of the difference is less than the defined tolerance (i.e. 0.000005), then the iteration is terminated.
Use the difference computed in step 2 to improve approximation of fraction. This is done by converting the difference into a fraction and adding (or subtracting) to the current approximation. In the example, a negative difference indicates a low approximation -- thus difference needs to be added to current approximation. The difference fraction is the numerator = 1 and denominator = 1/0.001176 = 850 -- difference in fraction from is 1/850. The new approximation will be (1/17) + (1/850) = (850*1 + 17*1)/(850*17) = 867/14450.
Repeat steps 2 to 4 until solution found.
After solution found, the fraction can be reduced. For example, 867/14450 is exactly 0.06 and the iteration process is terminated. 867/14450 can be reduced to 3/50.
Some features of this method are:
If the resulting fraction is 1/anything, the first approximation will be exact. For example, converting 0.25 to fraction, the first approximation will be 1/4. Thus further iterations are not needed.
In majority (> 80%) of 1,000,000 test cases, convergence occurs in 2 iteration or less.
For all test cases, the maximum number of iterations was 3.
I posted the code for this algorithm on github -- https://github.com/tnbezue/fraction
this is an interesting question.
I think you might be better off starting with reading about the multiples ways of calculating the "greatest common divisor" ( http://en.wikipedia.org/wiki/Greatest_common_divisor is a good source ).
Implement a quick&dirty algorithm that makes those calculations as you would do with a pen and paper then look into how doubles are represented (sign, exponent, mantissa) and improve your algorithm to take advantage of this representation.
sadly, there's not much more I can do without writing your piece of code.
An algorithm created with c++ that does decimal to fraction.
#include <iostream>
using namespace std;
// converts the string half of the inputed decimal number into numerical values
void converting (string decimalNumber, float& numerator, float& denominator )
{
float number;
string valueAfterPoint = decimalNumber.substr(decimalNumber.find(".") + 1,((decimalNumber.length() -1) )); // store the value after the decimal into a valueAfterPoint
cout << valueAfterPoint<< " "<< endl;
int length = valueAfterPoint.length(); //stores the length of the value after the decimal point into length
numerator = atof(valueAfterPoint.c_str()); // converts the string type decimal number into a float value and stores it into the numerator
// loop increases the decimal value of the numerator and the value of denominator by multiples of ten as long as the length is above zero of the decimal
cout << length<< endl;
for (; length > 0; length--)
{
numerator *= 10;
}
do
denominator *=10;
while (denominator < numerator);
}
// simplifies the the converted values of the numerator and denominator into simpler values for an easier to read output
void simplifying (float& numerator, float& denominator)
{
int maximumNumber = 9; //Numbers in the tenths place can only range from zero to nine so the maximum number for a position in a poisitino for the decimal number will be nine
bool isDivisble; // is used as a checker to verify whether the value of the numerator has the found the dividing number that will a value of zero
// Will check to see if the numerator divided denominator is will equal to zero
if(int(numerator) % int(denominator) == 0)
{
numerator /= denominator;
denominator = 1;
return;
}
//check to see if the maximum number is greater than the denominator to simplify to lowest form
while (maximumNumber < denominator)
{
maximumNumber *=10;
}
// the maximum number loops from nine to zero. This conditions stops if the function isDivisible is true
for(; maximumNumber > 0; maximumNumber --)
{
isDivisble = ((int(numerator) % maximumNumber == 0) && int(denominator)% maximumNumber == 0);
cout << numerator << denominator <<" " <<endl;
if(isDivisble)
{
numerator /= maximumNumber; // when is divisible true numerator be devided by the max number value for example 25/5 = numerator = 5
denominator /= maximumNumber; //// when is divisible true denominator be devided by the max number value for example 100/5 = denominator = 20
}
// stop value if numerator and denominator is lower than 17 than it is at the lowest value
int stop = numerator + denominator;
if (stop < 17)
{
return;
}
}
}
int main()
{
string decimalNumber;
float numerator = 0;
float denominator = 1;
cout << "Enter the decimal number";
cin >> decimalNumber;
//convert function
converting(decimalNumber, numerator, denominator);
//call simplyfication funcition
simplifying(numerator, denominator);
cout<< "Fraction: "<< numerator << "/" << denominator<< endl;
return 0;
}

Resources