The following is a sample prog
#include<stdio.h>
#include<math.h>
main()
{
int x;
scanf("%d",&x);
printf("%.2f\n",(1/pow(2,x)));
}
Here I give .2f for floating point formatting. We can also give respective .3f or .5f etc according to requirement.
Suppose we do not know till what decimal after the '.' it is to be printed. I want to give something like a value n through input, so that it prints decimals till the n.
like .nf if n = 5 and x =1, it prints 0.50000 and for n = 3 it should print 0.500
How do I achieve this?
You can specify the desired precision as a variable:
int n = 5;
printf("%.*f\n", n, (1.0/pow(2,x))); /* equivalent to %.5f */
Quoting from man 3 printf:
An optional precision, in the form of a period ('.') followed by an
optional decimal digit string. Instead of a decimal digit string one
may write "*" or "*m$" (for some decimal integer m) to specify that the
precision is given in the next argument, or in the m-th argument,
respectively, which must be of type int.
Related
somebody know how to represent the digits to the left of the decimal point?
I want to display the number 5 digits left to the point and 4 digits right to it/
for the exercise 12345/100 i want to get 00123.4500
printf("%010.4f", (double)12345/100);
man 3 printf says:
The overall syntax of a conversion specification is:
%[$][flags][width][.precision][length modifier]conversion
.4 means the floating point precision to print 4 decimals.
0 is a flag that means to pad with 0s.
10 is the width. If at the right of the decimal there are 4, and at the left there are 5, the total is 10 (with the dot).
While the answer of alinsoar is correct and the most common case, I would like to mention another possibility which sometimes is useful: fixed-point representation.
An uint32_t integer holds 9 decimal digits. We may choose to imagine a decimal point before the 4th digit from the right. The example would then look like this:
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>
int main(void)
{
uint32_t a = 123450000; // 12345.0000
uint32_t b = a / 100; // 123.4500
uint32_t i = b / 10000; // integer part
uint32_t f = b % 10000; // fractional part
printf("%05" PRIu32 ".%04" PRIu32, i, f); // 5 integer digits, 4 fractional digits
}
Using fixed-point one has to pay special attention to the value range and e.g. multiplication needs special handling, but there are cases where it is preferable over the floating-point representation.
i am facing problem while placing decimal point in my input string.please refer my code for better understanding.
Description:The field shall be eight (8) digits in width, right-aligned, zero-filled. Left most digit denotes the number of positions the decimal separator shall be move from the right.
Expected result should be like this :
example 1: 71234567
output 0.1234567
example 2 : 31234567
output : 1234.567
But when i run my code with above example i am getting below output.
output 1 : 0.123457
output 2 : 1234.567000
It should not need to append the zeroes in right hand side.why this is happening.could anyone please tell me.
Attached my code snippet:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
int main()
{
unsigned char str[8] = "31234567";
int num = atoi(str); //Convert string to int
printf("num = %d\n",num);
int FirstDigit = num;
num = num % (unsigned long)pow(10.0, (double)floor(log10(num)));
printf("After removing 1st digit from number = %d\n",num);
while(FirstDigit>=10)
{
FirstDigit = FirstDigit/10;
}
printf("Decimal position stored in FirstDigit = %d\n",FirstDigit);
printf("Final value = %f",num/pow(10,FirstDigit));
return 0;
}
For default printf gives 6 significant digits, if precision is not specified.
https://man7.org/linux/man-pages/man3/printf.3.html
g, G The double argument is converted in style f or e (or F or
E for G conversions). The precision specifies the number
of significant digits. If the precision is missing, 6
digits are given; if the precision is zero, it is treated
as 1. Style e is used if the exponent from its conversion
is less than -4 or greater than or equal to the precision.
Trailing zeros are removed from the fractional part of the
result; a decimal point appears only if it is followed by
at least one digit.
In your case you are trying to print the number 0.1234567 but in that number there are 7 significant digits. So printf rounds that number to 0.123457. You can specify precision like this.
printf("Final value = %.7f",num/pow(10,FirstDigit)); // (%.7f)
But you also want to get rid of the trailing zeros. For this you can use it like this.
printf("Final value = %.10g",num/pow(10,FirstDigit)); // (%.10g)
I specified precison as 10 because you are using int. Hence int can have at most 10 digits.
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');
}
Here's what I'm trying to do:
I need to print the fractional part of a floating number which has to be input as a float during user input.
The fractional part should be like: if float is 43.3423, the output should be 3423; and if number is 45.3400 output should be 3400.
This can be done easily with a string input but I need a way to make this work with float without losing the extra zeros or without appending zeros to user's original input.
Here's what I already tried :-
Take the fractional part by frac = num - (int)num and then multiplying frac until we get zero as the remainder. But this fails for cases like 34.3400 — the last two zeros won't get included with this method.
Convert the float number to a string by
char string[20];
sprintf(string, "%f", float_number);
The sprintf function puts the float number as a string but here also it doesn't automatically detect the user entered precision and fills the string with extra zeros at the end (6 total precision). So here also the information about the user's original entered precision is not obtained.
So, is there a way to get this done? The number must be taken as float number from user. Is there any way to get info about what's the user's entered precision? If it's not possible, an explanation would be very helpful.
I think I understand where you're coming from. E.g. in physics, it's a difference whether you write 42.5 or 42.500, the number of significant digits is implicitly given. 42.5 stands for any number x: 42.45 <= x < 42.55 and 42.500 for any x: 42.4995 <= x < 42.5005.
For larger numbers, you would use scientific notation: 1.0e6 would mean a number x with x: 950000 <= x < 1050000.
A floating point number uses this same format, but with binary digits (sometimes called bits ;)) instead of decimal digits. But there are two important differences:
The number of digits (bits) used depends only on the data type of the floating point number. If your data type has e.g. 20 bits for the mantissa, every number stored in it will have these 20 bits. The mantissa is always stored without a part after the "decimal" (binary?) point, so you won't know how many significant bits there are.
There's no direct mapping between bits and decimal digits. You will need roughly 3.5 bits to represent a decimal digit. So even if you knew a number of significant bits, you still wouldn't know how many significant decimal digits that would make.
To address your problem, you could store the number of significant digits yourself in something like this:
struct myNumber
{
double value;
int nsignificant;
};
Of course, you have to parse the input yourself to find out what to place in nsignificant. Also, use at least double here for the value, the very limited precision of float won't get you far. With this, you could use nsignificant to determine a proper format string for printing the number with the amount of digits you want.
This still has the problem mentioned above: you can't directly map decimal digits to bits, so there's never a guarantee your number can be stored with the precision you intend. In cases where an exact decimal representation is important, you'll want to use a different data type for that. C# provides one, but C doesn't. You'd have to implement it yourself. You could start with something like this:
struct myDecimal
{
long mantissa;
short exponent;
short nsignificant;
}
In this struct, you could e.g. place 1.0e6 like this:
struct myDecimal x = {
.mantissa = 1;
.exponent = 6;
.nsignificant = 2;
};
Of course, this would require you to write quite a lot of own code for parsing and formatting these numbers.
which has to be input as a float during user input.
So, is there a way to get this done.
Almost. The "trick" is to note the textual length of user input. The below will remember the offset of the first non-whitespace character and the offset after the numeric input.
scanf(" %n%f%n", &n1, &input, &n2);
n2 - n1 gives code the length of user input to represent the float. This method can get fooled if user input is in exponential notation, hexadecimal FP notation, infinity, Not-a-number, excessive leading zeros, etc. Yet works well with straight decimal input.
The idea is to print the number to a buffer with at least n2 - n1 precision and then determine how much of the fractional portion to print.
Recall that float typically has about 6-7 significant leading digits of significance, so attempting to input text like "123456789.0" will result in a float with the exact value of 123456792.0 and the output will be based on that value.
#include <float.h>
#include <math.h>
int scan_print_float(void) {
float input;
int n1, n2;
int cnt = scanf(" %n%f%n", &n1, &input, &n2);
if (cnt == 1) {
int len = n2 - n1;
char buf[len * 2 + 1];
snprintf(buf, sizeof buf, "%.*f", len, input);
char dp = '.';
char *p = strchr(buf, dp);
if (p) {
int front_to_dp = p + 1 - buf;
int prec = len - front_to_dp;
if (prec >= 0) {
return printf("<%.*s>\n", prec, p+1);
}
}
}
puts(".");
return 0;
}
int main(void) {
while (scan_print_float()) {
fflush(stdout);
}
return EXIT_SUCCESS;
}
Input/Output
43.3423
<3423>
45.3400
<3400>
-45.3400
<3400>
0.00
<00>
1234.500000
<500000>
.
.
To robustly handle this and the various edge cases, code should read user input as text and not as a float.
Note: float can typically represent about 232 numbers exactly.
43.3423 is usually not one of them. Instead it has an exactly value of 43.3423004150390625
43.3400 is usually not one of them. Instead it has an exactly value of 43.340000152587890625
The only way is to create a struct with the original string value and/ or required precision for rounding
int main()
{
system("color FC");
const float i=23.1234234;
printf("%5.4f",i);
getch();
return 0;
}
In above code , while printing float data type %5.4 format specifier is used.
I understood that .4 is used to get four numbers after decimal but whats the use of 5 before .4
The 5 is the length specifier. In this case, the printed float will take up at least 5 spaces. If it is shorter than that, leading spaces will be used.
(Though because of the precision 4, it will always be at least 6 characters long; the length modifier 5 in this case is a no-op.)
See documentation.
5 is used to right justify the output by 5 places i.e. the last digit will occur 5 places from cursor's initial position, if possible.
It is effective only when the length ( including the decimal ) is smaller than what is mentioned in the specifier.
e.g. printf("%5.4f",i);
till the specifier at the place of 5 is smaller than or equal than the length of the output
i.e 2(before decimal) + 4(after decimal, as chosen ) + 1 (the decimal itself) =7 , it has
no effect.
It will have effect here if it is at least 8.
At 7 it does what it should but you won's see any spaces.
5 is used to right justify the output by 5 places. Since the output is 10 character long so the effect is not seen. Now try this
#include <stdio.h>
int main()
{
const float i=23.1234234;
printf("%f\n",i);
printf("%5.4f\n",i);
printf("%7.4f\n",i);
printf("%10.4f\n",i);
printf("%12.5f",i);
return 0;
}
Output:
23.1234234
23.1234
23.1234
23.1234
23.1234