So I am trying to round DOWN to 2 decimal places in C - EDIT: I actually need to change the value, not just display it to 2 decimals.
For example:
double x = 0.1234;
x = 0.12;
double y = 3.14159;
y = 3.14;
Is the an integrated function in <math.h> similar to floor(), or is there another way to do this?
Well I need to value to change so I used x = (double)((int)(x*100))/100;
This works, but you are limited to a relatively low range, i.e: 123456789 * 100 overflows.
Check if modf helps:
#include <stdio.h>
#include <math.h>
double dec2(double number)
{
double fractpart, intpart;
fractpart = modf(number, &intpart);
return intpart + round(fractpart * 100) * 0.01;
}
int main(void)
{
printf("%f\n", dec2(0.1234));
printf("%f\n", dec2(3.14159));
return 0;
}
Output:
0.120000
3.140000
If you want to display a float or double with 2 decimal places, specify a precision of 2 when using the %f format specifier.
printf("x=%.2f", x);
Related
The teacher asks to remove the pi subtraction cycle in the main function. I don’t know how to write the program so that the correct results will come out for any values.
#include <stdio.h>
#include <math.h>
double sinus(double x);
int main(void) {
double a, x;
scanf("%le", & x);
a = x;
while (fabs(x) > 2 * (M_PI)) {
x = fabs(x) - 2 * (M_PI);
}
if (a > 0)
a = sinus(x);
else a = (-1) * sinus(x);
printf("%le", (double) a);
return 0;
}
double sinus(double x) {
double sum = 0, h, eps = 1.e-16;
int i = 2;
h = x;
do {
sum += h;
h *= -((x * x) / (i * (i + 1)));
i += 2;
}
while (fabs(h) > eps);
return sum;
return 0;
}
#include <stdio.h>
#include <math.h>
double sinus(double x);
int main(void)
{
double a,x;
scanf("%le",&x);
a=x;
x=fmod(fabs(x),2*(M_PI));
if(a>0)
a=sinus(x);
else a=(-1)*sinus(x);
printf("%le",(double)a);
return 0;}
double sinus(double x)
{
double sum=0, h, eps=1.e-16; int i=2;
h=x;
do{
sum+=h;
h*=-((x*x)/(i*(i+1)));
i+=2;}
while( fabs(h)>eps );
return sum;
return 0;
}
… how to write the program so that the correct results will come out for any values.
OP's loop is slow with large x and an infinfite loop with very large x:
while (fabs(x) > 2 * (M_PI)) {
x = fabs(x) - 2 * (M_PI);
}
A simple, though not high quality solution, is to use fmod() in the function itself. #Damien:
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
double sinus(double x) {
x = fmod(x, 2*M_PI); // Reduce to [-2*M_PI ... 2*M_PI]
...
Although function fmod() is not expected to inject any error, the problem is that M_PI (a rational number) is an approximation of π, (an irrational number). Using that value approximation injects error especially x near multiplies of π. This is likely OK for modest quality code.
Good range reduction is a problem as challenging as the trigonometric functions themselves.
See K.C. Ng's "ARGUMENT REDUCTION FOR HUGE ARGUMENTS: Good to the Last Bit" .
OP's sinus() should use additional range reduction and trigonometric properties to get x in range [-M_PI/4 ... M_PI/4] (example) before attempting the power series solution. Otherwise, convergence is slow and errors accumulate.
I have the following source code but the result is not rounding to 2 decimal places.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(int argc, char *argv[])
{
float x1=0;
float x2 = 0;
float result=0;
x1 = 8961.650391;
result = x1 * 100 + 0.5;
result = (float)floor(result);
printf("Result = <%f>\n", result);
result = result/100;
x2 = result;
printf("x2 = <%f>\n", x2);
return 0;
}
Please help to resolve the problem.
Result = <896165.000000>
x2 = <8961.650391>
How can obtain x3 = 8961.650000?
use "%0.2f" instead of %f , it will print value upto 2 decimal
x2= roundf(result * 100) / 100;
printf("x2 = <%0.2f>\n", x2);
float can typically represent about 232 different numbers exactly.
After all, it is typically encoded using 32-bits.
8961.65 is not one of them. The closest float to 8961.65 is 8961.650390625f. The below shows the previous and subsequent float.
To print a float to the nearest 0.01, use "%.2f" as suggest well by #pritesh agrawal.
Recommend rounding with rint() or round().
int main(void) {
float x = 8961.650391f;
float x100 = rint(x * 100.0);
float result = x100 / 100.0f;
printf("%f %.2f\n", nextafterf(x, 0), nextafterf(x, 0));
printf("%f %.2f\n", x, x);
printf("%f %.2f\n", nextafterf(x, x * 2), nextafterf(x, x * 2));
printf("%f %.2f\n", x100, x100);
printf("%f %.2f\n", result, result);
return 0;
}
Output
8961.649414 8961.65
8961.650391 8961.65
8961.651367 8961.65
896165.000000 896165.00
8961.650391 8961.65
How can obtain x3 = 8961.650000?
x3 cannot have the exact value of 8961.650000. To print a value, rounded to 2 decimal places followed by 4 zeros, the below can be used, but it is a bit of chicanery.
printf("%.2f0000\n", 8961.650390625f);
// output 8961.650000
I am trying to calculate Maxwell-Boltzmann Distribution but this code gives 0.00000, what is the problem?
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
float e=2.718228183, pi=3.14159265, m=2.66*pow(10,-23), t, k=1.38*pow(10,-23), v, result;
scanf("%f %f", &t, &v);
result = sqrt(pow( m / (2*pi*k*t), 3)) * 4 * pi * pow(v,2) * pow(e, -(m * pow(v,2)) / (2*k*t));
printf("%f", result);
}
As described in the comments, the use of float together with the reduced precision of the constants give a result that is not representable anymore as a float. Changing the data type to double alone gives two decimal digits of accuracy. If we use exp, more digits for pi and do a bit of recombination of the computations we get 12 digits of accuracy. E.g.:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double pi = 3.1415926535897932384626433832795028842, m = 2.66e-23, k =
1.38e-23;
double t, v, v2, dkt, result;
// check omitted
scanf("%lf %lf", &t, &v);
v2 = v * v;
dkt = 2 * k * t;
result = pow(m / (pi * dkt), 3 / 2.0) * 4 * pi * v2 * exp(-(m * v2) / (dkt));
printf("%.20g\n", result);
return 0;
}
The result from Pari/GP is 8.1246636077915008261803395870165527173e-9 and the result we get with the code above is 8.1246636077914841125e-09. Without the intermediate results v2, dkt and the replacement of sqrt we got 8.1246636077914824582e-09, not much of a difference, especially with accuracy where it gained nothing.
If you want the full 16 decimal digits of accuracy you need to take the whole thing apart and take a different approach.
replace
double pi=acos(-1.);
instead of
double pi=3.1415926535897932384626433832795028842;
I don't really know how to explain this (that's why the title was to vague) but I need a way to make C divide in a certain way, I need to make c divide without any decimals in the answer (besides the remainder) for example;
Instead of 5.21 / .25 = 20.84
I need this 5.21 / .25 = *20* Remainder = *.21*
I found out how to find the remainder with Fmod() but how do I find the 20?
Thanks ~
how about using implicit casts?
float k = 5.21 / .25;
int n = k;
k -= n;
results in
k = .84
n = 20
using only ints will also do the job if you don't need the remainder
int k = 5.21 / .25
will automatically truncate k and get k = 20
Use double modf(double value, double *iptr) to extract the integer portion of a FP number.
The modf functions break the argument value into integral and fractional parts, each of which has the same type and sign as the argument. C11 §7.12.6.12 2
#include <math.h>
#include <stdio.h>
int main() {
double a = 5.21;
double b = 0.25;
double q = a / b;
double r = fmod(a, b);
printf("quotient: %f\n", q);
printf("remander: %f\n", r);
double ipart;
double fpart = modf(q, &ipart);
printf("quotient i part: %f\n", ipart);
printf("quotient f part: %f\n", fpart);
return 0;
}
Output
quotient: 20.840000
remander: 0.210000
quotient i part: 20.000000
quotient f part: 0.840000
Using int is problematic due to a limited range, precision and sign issues.
I have written a C program (which is part of my project) to round off a float value to the given precision specified by the user. The function is something like this
float round_offf (float num, int precision)
What I have done in this program is convert the float number into a string and then processed it.
But is there a way to keep the number as float itself and implement the same.
Eg. num = 4.445 prec = 1 result = 4.4
Of course there is. Very simple:
#include <math.h>
float custom_round(float num, int prec)
{
int trunc = round(num * pow(10, prec));
return (float)trunc / pow(10, prec);
}
Edit: it seems to me that you want this because you think you can't have dynamic precision in a format string. Apparently, you can:
int precision = 3;
double pie = 3.14159265358979323648; // I'm hungry, I need a double pie
printf("Pi equals %.*lf\n", precision, pie);
This prints 3.142.
Yes:
float round_offf(float num, int precision)
{
int result;
int power;
power = pow(10, precision + 1);
result = num * power;
if ((result % 10) > 5)
result += 10;
result /= 10;
return ((float)result / (float)power);
}