Function to add two fractions and output decimal only giving 0 - c

I'm trying to make a simple program which adds two fractions. It takes four numbers as inputs:
numerator and denominator of the first fraction and numerator and denominator of the second fraction. The output should be the sum of the two fractions in decimal form. My program isn't working and I'm stuck with how to fix it. It outputs 0.000 for all of the examples tried to run the function.
# include <stdio.h>
int fracsum(float n1, float d1, float n2, float d2)
{
float n3, d3;
double res;
n3 = (n1*d2) + (d1*n2);
d3 = d1 * d2;
res = n3 / d3;
return res;
}
int main(void)
{
printf("%.3f %.3f %.3f\n",
fracsum(1,2,2,4),
fracsum(1,4,1,8),
fracsum(4,3,5,6));
return 0;
}
The output of this code is: 0.000 0.000 0.000

int fracsum
but you clearly want
double fracsum
from your printf call

Related

Why does this code not work for all inputs (Cosine of an angle using Taylor series). Specifically for angles greater than 90 degrees?

This was a homework problem to find cosine of an angle without using the inbuilt cos function
I wrote the following code:
// Program to find cos x using loop.
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
double cosine(double);
int main()
{
double x;
printf("Enter angle in degrees: ");
scanf("%lf", &x);
x = x*M_PI/180.0;
printf("The value of cos(%lf) is %lf", x, cosine(x));
}
double cosine(double x)
{
double previous, current = 1;
double denominator = 1*2, numerator = x*x;
double sign = -1;
while(1)
{
previous = current;
current = current + ((numerator)/(denominator))*sign;
denominator = denominator * (denominator+1) * (denominator+2);
numerator = numerator*x*x;
sign = -sign;
if (fabs(previous - current)<=0.0001)
{
break;
}
}
return current;
}
For x = 180 the answer isn't -1 (which is the correct one)
I have no clue what is going wrong here. Please help I am relatively new at programming.
I tested out your code and found an error in the derivation of the factorial value for your denominator. The following line of code was actually not providing a proper factorial value.
denominator = denominator * (denominator+1) * (denominator+2);
It actually was increasing the denominator value too fast.
With that in mind, I did a bit of refactoring including revising the "while" loop test for previous and current to a simple "for" loop with enough iterations to provide the precision you most likely need. Following is a refactored version of your program.
// Program to find cos x using loop.
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
double cosine(double);
int main()
{
double x;
printf("Enter angle in degrees: ");
scanf("%lf", &x);
x = x * M_PI / 180.0;
printf("The value of cos(%lf) is %lf\n", x, cosine(x));
}
double cosine(double x)
{
double current = 1.00;
double denominator = 2.00, numerator = x*x;
double factor = 2.00;
double sign = -1;
for(int i = 0; i < 16; i++)
{
current = current + ((numerator)/(denominator))*sign;
denominator = denominator * (factor+1.00) * (factor+2.00); /* Derives the proper factorial increase */
numerator = numerator * x * x;
sign = -sign;
factor = factor + 2.00;
}
return current;
}
Some points to note.
Instead of the previous formula for calculating the needed factorial, a work field for keeping track of the ascending factorial values is added and incremented as needed and utilized in the denominator calculation.
Instead of testing for smaller and smaller differences with the "while" loop, a "for" loop is utilized with enough iterations to provide a desired precision for the cosine value.
With those tweaks, following were some tests listed at the terminal.
#Vera:~/C_Programs/Console/Taylor/bin/Release$ ./Taylor
Enter angle in degrees: 0
The value of cos(0.000000) is 1.000000
#Vera:~/C_Programs/Console/Taylor/bin/Release$ ./Taylor
Enter angle in degrees: 90
The value of cos(1.570796) is 0.000000
#Vera:~/C_Programs/Console/Taylor/bin/Release$ ./Taylor
Enter angle in degrees: 180
The value of cos(3.141593) is -1.000000
#Vera:~/C_Programs/Console/Taylor/bin/Release$ ./Taylor
Enter angle in degrees: 270
The value of cos(4.712389) is 0.000000
#Vera:~/C_Programs/Console/Taylor/bin/Release$ ./Taylor
Enter angle in degrees: 360
The value of cos(6.283185) is 1.000000
Give those tweaks a try and see if it meets the spirit of your project.

Why is average calculating program showing different results after decimal points?

**While runnning the C program the output is 33.000
Meanwhile the correct answer is 33.200
what is wrong is there any data return type issue with float,
so Should I use double data type I getting i head stuck **
#include <stdio.h>
float passingmarksArrray(int studentmarks[5]);
int main(){
float studentmarks_Average ;
int marks[5] = {21, 24, 32, 45, 44};
studentmarks_Average = passingmarksArrray(marks);
printf("The average marks of the student is %.3f \n", studentmarks_Average );
return 0;
}
float passingmarksArrray(int studentmarks[5]){
int i;
int sumofmarks = 0;
float average;
for (int i = 0; i < 5; ++i)
{
sumofmarks = sumofmarks + studentmarks[i];
}
average = (sumofmarks / 5) ;
return average;
}
The problem is, the statement
(sumofmarks / 5) ;
is an integer division, which will not yield a floating point result. To obtain a floating point result, you need to enforce floating point division, by saying
(sumofmarks / (float)5) ;
or
(sumofmarks / 5.0) ;
In the expression (average = (sumofmarks / 5))
sumofmarks / 5 returns an integer value which is then converted to float and stored in average.
while sumofmarks / 5.0 returns float value.

Problems with rounding a float number

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

Calculating Maxwell-Boltzmann Distribution

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;

Division issues in C

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.

Resources