Why is my code not reversing a two digit number? - c

I am trying to reverse a two digit number, and I understand there may be better ways of doing this, but I am curious now why the way I chose does not work.
If I input 48, it produces 84 (a successful reversal).
If I input 84, it produces 38. If I input 47, it produces 64. These are just some examples of unsuccessful reversals.
int digit_one, digit_two, input;
float a, b;
printf("Enter a two-digit number: ");
scanf("%d", &input);
a = input * 0.1; // turns the two digit input figure into a float with a digit after the decimal point
digit_one = a; // turns the float into an integer, eliminating the digit after the decimal point
b = a - digit_one; // produces a float that has a 0 before the decimal point, and a digit after the decimal point
digit_two = b * 10; // moves the digit that was after the decimal point, to before the decimal point
printf("The reversal is: %d%d\n", digit_two, digit_one);
Thank you!

a - digit_one is a fractional number. If it's slightly less than the exact result (because for example 0.7 cannot be represented exactly as a float), then (a - digit_one) * 10 will be slightly less than the desired integer, and so digit_two will be one less than you expect.
You can avoid floating point, and write int digit_one, digit_two = input / 10, input % 10;

Working with floats is not the best approach here. With the input "84", b * 10 = 3.999996 which is 3 when you convert it to an integer.
This is a classic computer science problem with floats. Here are some links where this has been explained very well:
Is floating point math broken?
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Your problem can be solved differently:
int digit_one, digit_two, input, a, b;
printf("Enter a two-digit number: ");
scanf("%d", &input);
digit_one = input % 10;
digit_two = (input / 10) % 10;
printf("The reversal is: %d%d\n", digit_one, digit_two);

int result =0;
do{
result = (result * 10) + (input % 10);
input /= 10;
} while(input)
printf("The reversal is: %d\n", result);
You can print the 'result' variable to get any integer value irrespective of 2 digit or 3 digit

Related

How to set the level of precision for the decimal expansion of a rational number

I'm trying to print out the decimal expansion of a rational number in C. The problem I have is that when I divide the numerator by the denominator I lose precision. C rounds up the repeating part when I don't want it to.
For example, 1562/4995 = 0.3127127127... but in my program I get 1562/4995 = 0.312713. As you can see a part of the number that I need has been lost.
Is there a way to specify C to preserve a higher level of decimal precision?
I have tried to declare the result as a double, long double and float. I also tried to split the expansion into 2 integers seperated by a '.'
However both methods haven't been successful.
int main() {
int numerator, denominator;
numerator = 1562;
denominator = 4995;
double result;
result = (double) numerator / (double) denominator;
printf("%f\n", result);
return 0;
}
I expected the output to be 1562/4995 = 0.3127127127... but the actual output is 1562/4995 = 0.312713
The %f format specifier to printf shows 6 digits after the decimal point by default. If you want to show more digits, use a precision specifier:
printf("%.10f\n", result);
Also, the double type can only accurately store roughly 16 decimal digits of precision.
You need to change your output format, like this:
printf("%.10lf\n", result);
Note two things:
The value after the . specifies the decimal precision required (10 decimal places, here).
Note that I have added an l before the f to explicitly state that the argument is a double rather than a (single-precision) float.
EDIT: Note that, for the printf function, it is not strictly necessary to include the l modifier. However, when you come to use the 'corresponding' scanf function for input, it's absence will generate a warning and (probably) undefined behaviour:
scanf("%f", &result); // Not correct
scanf("%lf", &result); // Correct
If printing is all you want to do, you can do this with the same long division you were taught in elementary school:
#include <stdio.h>
/* Print the decimal representation of N/D with up to
P digits after the decimal point.
*/
#define P 60
static void PrintDecimal(unsigned N, unsigned D)
{
// Print the integer portion.
printf("%u.", N/D);
// Take the remainder.
N %= D;
for (int i = 0; i < P && N; ++i)
{
// Move to next digit position and print next digit.
N *= 10;
printf("%u", N/D);
// Take the remainder.
N %= D;
}
}
int main(void)
{
PrintDecimal(1562, 4995);
putchar('\n');
}

how to divide the float number into 2 or 3 pieces

So I just received my paper. its said if the input number is 0.001001001 (repeated) it's gonna print 0.001..., if it's 0.015015015, then 0.015... as a print, if the number is 998 its should be 0.998... my idea is to divide it into something like 2 pieces but im still cant figure its out. thanks
scanf("%f",&num1);
scanf("%f",&num2);
scanf("%f",&num3);
num1 = floor(1000*(num1/999))/1000;
num2 = floor(1000*(num2/999))/1000;
num3 = floor(1000*(num3/999))/1000;
printf("%.3f...\n",num1);
printf("%.3f...\n",num2);
printf("%.3f...\n",num3);
input = 3 integers that divide to 999, the value is below 999
output = the result, if the result repeated (0.001001001) then its going to print out 0.001...
sample :
input = output
3 = 0.003...
10 = 0.010...
998 = 0.998...
Note: I tried it with the floor so i guess there's something error about my logic
Since the value is below 999, 999 not included, just read the integer, and print it with 0.%03d...:
int num;
scanf("%d", &num);
printf("0.%03d...\n", num);
The conversion specification %03d will print the given integer in base-10, with leading zeroes prepended so that it is at least 3 characters wide. For 3, it will print 003, for 10 it will print 010 and for 976 it will print 976.
What you specifically cannot do this with are floats. Floats in your computer are binary numbers and they cannot precisely produce decimal fractions... nor can they do infinite precision.
Ifx is near some 0.abcabcabc... pattern, scale is by *999 and then /1000.
abc.abcabc... 1000x
- 0.abcabcabc... 1x
-------------------
abc. 999 x
/ 1000
-------------------
0.abc
Mathematically this works to exact 3 digits. Yet we are working with double.
double is usual encoded as binary64 and can not exactly represent, 0.001..., 0.015..., 0.998... and so the above idea will result in values very near the intended. The * 999 and / 1000 steps may impart a small departure from the mathematical result too.
int cajunb_print(double x) {
printf("(before %.*e) ", DBL_DECIMAL_DIG, x);
x = x * (1000 - 1) / 1000;
printf("(after %.*e) ", DBL_DECIMAL_DIG, x);
return printf("%.3f...\n", x);
}
int main(void) {
cajunb_print(0.001001001001001001);
cajunb_print(0.015015015015015015);
cajunb_print(0.998998998998998998);
return 0;
}
Output
(before 1.00100100100100099e-03) (after 1.00000000000000002e-03) 0.001...
(before 1.50150150150150149e-02) (after 1.49999999999999994e-02) 0.015...
(before 9.98998998998999022e-01) (after 9.97999999999999998e-01) 0.998...

Program to convert print floating point value as fraction not working..?

So I am trying to write a program which takes a floating point value and represents it in terms of a fraction. I am facing a weird problem. This is my program:
#include<stdio.h>
#include<math.h>
int gcd(int,int);
void main()
{
int n,n1,n2,g;
float a,a1;
printf("Enter number of digits after decimal point: ");
scanf("%d",&n);
printf("Enter number: ");
scanf("%f",&a);
n2=pow(10,n);
a1=a*n2;
n1=(int)a1;
g=gcd(n1,n2);
n1/=g;n2/=g;
printf("The number is %d/%d",n1,n2);
}
int gcd(int a,int b)
{
int x,flag=0;
int n1=((a>b)?a:b);
int n2=((a<b)?a:b);
for(x=n1;x>=1;x--)
{
if(n1%x==0 && n2%x==0)
{
flag=1;break;
}
}
if(flag==1)
return x;
else
return 1;
}
Now this program gives the correct answer for numbers with only 1 decimal point. For example:
Enter number of digits after decimal point: 1
Enter number: 2.5
The number is 5/2
However for number with two or more digits after decimal point it gives a wrong answer. For example:
Enter number of digits after decimal point: 2
Enter number: 2.50
The number is 247/99
I know that floating point numbers are not accurate but I did not expect this big a variation. Is there any way to work around this and make this program work???
Works for me. I believe the reason is that you use pow(10, n) and pow is inexact on your platform. Use a simple for-loop instead:
n2 = 1;
for (int c = 0; c < n; c++) {
n2 *= 10;
}
As functions like pow(10, n) may generate results near an integer value instead of an exact integer value. Rather than truncating with (int), use one of the round functions should you want to continue using pow().
Consider long int lround(double x), long int lroundf(float x) which round and covert to an integer type in one call.
The lround and llround functions round their argument to the nearest integer value, rounding halfway cases away from zero, regardless of the current rounding direction. C11 ยง7.12.9.7 2
n2 = lround(pow(10,n));
a1 = a*n2;
n1 = lroundf(a1);

C program to round numbers, rounded to second position after the decimal place [duplicate]

This question already has answers here:
How do I restrict a float value to only two places after the decimal point in C?
(17 answers)
Closed 8 years ago.
I am writing a simple program to round numbers. It works fine when I enter something like 1.4 (gives me 1.0) or 2.6 (gives me 3.0). But when I enter 1.45, it should give me 1.5 but it prints 1.0. Or for 2.85 (should be 2.9, it prints 3.0). How do I make this work? I cannot use any functions.
#include<stdio.h>
const float add = 0.5;
int main(void)
{
float v;
printf("Please enter a value to be rounded: ");
scanf("%f", &v);
v = v + add;
v = (int)v;
printf("The rounded value is %.2f", v);
return 0;
}
Try this code. You need to break your floating value into Modulus and Dividend.
#include<stdio.h>
int main(void)
{
float v;
int con, r_value, mul;
printf("Please enter a value to be rounded: ");
scanf("%f", &v);
mul=v*10;
con=mul%10;
r_value=mul/10;
if(con>=5)
r_value=r_value+1;
else
r_value=r_value;
printf("The rounded value is %.2d", r_value);
return 0;
}
Above code is modified to be used for Negative Numbers also.
float v;
int con, r_value, mul;
printf("Please enter a value to be rounded: ");
scanf("%f", &v);
mul=v*10;
con=mul%10;
r_value=mul/10;
if(v>0)
{
if(con>=5)
r_value=r_value+1;
else
r_value=r_value;
}
else if (v<0)
{
if(con<=-5)
r_value=r_value-1;
else
r_value=r_value;
}
printf("The rounded value is %.2d", r_value);
Int value simply removes the value after decimal point it does't round of to nearest number
In your case when you give 2.45
2.45 + 0.5 = 2.95
which is rounded off to 2(2.0 since your asking for precision) i.e the decimal part is truncated not rounded off.
Ints do not have decimal places, so a cast from float to int then back to float will leave only the integer value.
Your subject (rounding to the second decimal place) does not match your question (rounding to an arbitrary position based on the input). That makes it difficult to answer your question properly.
That said, your code
v = v + 0.5;
v = (int)v;
will round a number to the nearest integer. I'm not sure why you expect the int cast to do anything else.
You are using v = (int)v;, how can it give 1.5 for input of 1.45.
To get what you want, you can just print the decimal digits 1 less than in original, i.e.
Suppose you have 2.455 which has 3 decimal digits, you can just print that number using %.2f and it will automatically be rounded off.
You can do:
printf("%.2f", ((int)(v * 100 + 0.5) / 100.0));

Binary manipulation in C

I am having some problems with writing a program for adding, subtracting, multiplying and dividing binary. the major problem i am having is being able to restricting the program to give output of 1s and 0s (the binary part) and also it needs to be able to manipulate the binary if it as decimals in them such as 101.1 or 1.0101. Below is a program i have found online during my research but i dont fully understand how it works as yet to implement my own nor does it capable of computing binary with decimals in them. I do not want to use arrays as it limits the maximum output depending on the bits you put aside to do these calculations.
Looking forward to some potential ideas.
#include<stdio.h>
int main(){
long int binary1,binary2;
int i=0,remainder = 0,sum[20];
printf("Enter any first binary number: ");
scanf("%ld",&binary1);
printf("Enter any second binary number: ");
scanf("%ld",&binary2);
while(binary1!=0||binary2!=0){
sum[i++] = (binary1 %10 + binary2 %10 + remainder ) % 2;
remainder = (binary1 %10 + binary2 %10 + remainder ) / 2;
binary1 = binary1/10;
binary2 = binary2/10;
}
if(remainder!=0)
sum[i++] = remainder;
--i;
printf("Sum of two binary numbers: ");
while(i>=0)
printf("%d",sum[i--]);
return 0;
}
That code may work if you have fixed-point decimal numbers.
I'd suggest to parse the string to a double number and then use the standard arithmetic.
To parse the number you split the string on the "." decimal separator.
You parse the integer part from right to left multiplying the ones and the zeroes by growing powers of two, starting from 0. Then you parse the other string (decimal part) multiplying by the inverse of growing powers of two, starting from one.
For example:
110.11001
110 + 11001
Integer, reversed = 0*2^0 + 1*2^1 + 1*2^2
Decimal = 1*2^-1 + 1*2^-2 + 0*2^-3 + 0*2^-4 + 1*2^-5

Resources