C Program to Calculate Hypotenuse - c

I'm fairly new to coding and am currently learning C. In class I was given an assignment to write a program that calculates the hypotenuse of the triangle by using our own functions. However, there seems to be something wrong with the code that I have written.
#include <stdio.h>
#include <math.h>
double hypotenuse(double x, double y, double z);
int main(void) {
double side1, side2, side3, counter;
side3 = 1;
for (counter = 0; counter <= 2; counter++) {
printf("Enter values for two sides: ");
scanf_s("%d %d", &side1, &side2);
printf("%.2f\n", hypotenuse(side1, side2, side3));
}
return 0;
}
double hypotenuse(double x, double y, double z) {
x *= x;
y *= y;
z = sqrt(x + y);
return z;
}
My instructor said that we're allowed to use the square root function sqrt of the math library. The main errors that I'm facing are:
1) side3 is not defined (This is why I just arbitrarily set it to 1, but is there some other way to prevent this error from happening?)
2) If I, for example, inputted 3 and 4 as side1 and side2, then side3 should be 5. However, the printed result is an absurdly long number.
Thank you for the help! Any words of advice are appreciated.

You don't need side3 variable - it is not used in calculation. And you function hypotenuse returns the result, so you can directly output the result of sqrt.

I use Ubuntu Linux and write it this way. Please look if you like it.
#include <stdio.h>
#include <math.h>
double hypotenuse(double x, double y) {
double z = sqrt(x * x + y * y);
return z;
}
int main(void) {
double b1, b2, counter;
for (counter = 0; counter <= 2; counter++) {
printf("Enter values for two sides: ");
scanf("%lf %lf", &b1, &b2);
printf("%.2f\n", hypotenuse(b1, b2));
}
return 0;
}
Test
$ ./a.out
Enter values for two sides: 1 1.73
2.00

OP's code has some problems:
Key problem: Code should have generated a compiler warning as scanf() is directed to treat &side1 as an int *. Turn on all compiler warnings to save you time. Code used "%d" rather than the matching "%lf" to read a double. Also the return value should be checked to validate input.
double side1, side2, side3, counter;
...
// scanf_s("%d %d", &side1, &side2);
if (scanf_s("%lf %lf", &side1, &side2) != 2) puts("Input error");
size3 is not needed. Call hypotenuse() with 2 arguments. #ghostprgmr
// printf("%.2f\n", hypotenuse(side1, side2, side3));
printf("%.2f\n", hypotenuse(side1, side2));
// double hypotenuse(double x, double y, double z) {
double hypotenuse(double x, double y) {
double z = ...
Minor: Code used "%.2f" to print the value of the hypotenuse. This may be OK with select input values to OP's code, but is a poor choice, in general. If input values are vary small like 0.001 and 0.002, the output will print rounded value of 0.00. With very large values, the result will show many non-important digits as OP found with 130899030500194208680850288727868915862901750748094271410143‌​232.00.
For development and debugging, consider using "%e" ,"%g" or "%a" to see a relevant double.
Note that x * x + y * y is prone to over/under flow, even when mathematically sqrt(x * x + y * y) is in the double range. That is one advantage of the standard function hypot(x,y) as it usually handles those edge cases well.

As a reference for anyone viewing this question:
You don't need to write your own function. Standard C provides functions to calculate the hypotnuse:
7.12.7.3 The hypot functions
Synopsis
#include <math.h>
double hypot(double x, double y);
float hypotf(float x, float y);
long double hypotl(long double x, long double y);
Note that you likely need to link with -lm, though that's not listed explicitly in the function documentation in the C standard nor the latest POSIX documentation. It might be documented elsewhere in the standards.
(Link to C11 [draft] standard - likely to be much longer-lived.)

Use correct format specifiers!
Format Specifier for double is not %d! Rest is fine.
#include <stdio.h>
#include <math.h>
double hypotenuse(double x, double y, double z);
int main(void) {
double side1, side2, side3, counter;
side3 = 1;
for (counter = 0; counter <= 2; counter++) {
printf("Enter values for two sides: ");
scanf("%lf %lf", &side1, &side2);
printf("%.2f\n", hypotenuse(side1, side2, side3));
}
return 0;
}
double hypotenuse(double x, double y, double z) {
x *= x;
y *= y;
z = sqrt(x + y);
return z;
}
Also you could modify it to this:
#include <stdio.h>
#include <math.h>
double hypotenuse(double x, double y);
int main(void) {
double side1, side2, counter;
for (counter = 0; counter <= 2; counter++) {
printf("Enter values for two sides: ");
scanf("%lf %lf", &side1, &side2);
printf("%.2f\n", hypotenuse(side1, side2));
}
return 0;
}
double hypotenuse(double x, double y) {
x *= x;
y *= y;
return sqrt(x + y);
}

Related

Solution to heat equation

When trying to plot the solution of the heat PDE I've found some troubles. The solution that I've found is:
Here is the code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define N 10000
double f(double x);
double X[N];
double Y[N];
int main(){
int i;
double b=43351/94400;
double dx=0.0001;
X[0]=0;
Y[0]=b;
for (i=1; i<N; i++){
X[i]=X[i-1]+dx;
Y[i]=f(X[i]);
}
FILE* output;
output = fopen("dades.txt", "w");
fprintf(output, "x Posició Temperatura\n");
for (i = 0; i < N; i++){
fprintf(output, "%lf %lf %lf\n", i*dx, X[i], Y[i]);
}
fclose(output);
return 0;
}
double f(double x){
int n;
double b=43351/94400;
for (n=1; n<N; n+=2){
double pi=3.14159265358979323846;
double t0=0.025;
double result=b;
result+=2*(1-pow((-1),n))/(pi*n)*(1-exp(-pow(n,2)*pow(pi,2)*pow(t0,2)))/(pow(n,2)*pow(pi,2))*sin(n*pi*x);
}
return result;
}
What I'm trying to do is to declare a function that calculates the infinite sum for n odd, and then looping it for every x between 0 and 1. The problem is that I don't know how to declare "result" in order to be the sum of all the terms, because if I declare it outside the for loop it doesn't satisfy the boundary conditions.
(Note that I fixed t=0.025).
According to the equation, you can implement f as:
#define M_PI 3.14159265358979323846;
double f(double x)
{
int n;
double result=43351.0/94400.0;
double t0=0.025;
for (n=1; n<N; n+=2){
result+=2*(1-pow((-1),n))/(M_PI*n)*(1-exp(-pow(n,2)*pow(M_PI,2)*pow(t0,2)))/(pow(n,2)*pow(M_PI,2))*sin(n*M_PI*x);
}
return result;
}
Since you are using double, so you have to explicitly add a .0 otherwise it may be considered as integer.
The declarations of variable are moved outside the loop in order both to clarify the code and ensure the variable result gets update instead of being overwritten.
EDIT:
You could improve the function f to take the value of t as an input. This also aligns with the equation provided. It would then implements this way:
double f(double x, double t)
{
int n;
double result=43351.0/94400.0;
for (n=1; n<N; n+=2){
result+=2*(1-pow((-1),n))/(M_PI*n)*(1-exp(-pow(n,2)*pow(M_PI,2)*pow(t,2)))/(pow(n,2)*pow(M_PI,2))*sin(n*M_PI*x);
}
return result;
}
EDIT:
The implementation of the math of the equation could be further simplified:
a^2 b^2 is same as (ab)^2.
(-1)^n with n odd is always -1.
2*(1-pow((-1),n)) is a replacement for 4.
Plus, from a performance perspective you can avoid recalculation of repeated terms by putting them in a variable and the use it as you need (for instance the n^2 pi^2).

Calculating $\sqrt[3]{x}$ with Babylonian method

Consider my attempt to implement the Babylonian method in C:
int sqrt3(int x) {
double abs_err = 1.0;
double xold = x;
double xnew = 0;
while(abs_err > 1e-8) {
xnew = (2 * xold + x/(xold* xold))/3;
abs_err= xnew-xold;
if (abs_err < 0) abs_err = -abs_err;
xold=xnew;
}
return xnew;
}
int main() {
int a;
scanf("%d", &a);
printf(" Result is: %f",sqrt3(a));
return 0;
}
Result is for x=27: 0.0000?
Where is my mistake?
While the function returns an int, that value is printed with the wrong format specifier, %f instead of %d.
Change the signature (and the name, if I may) into something like this
double cube_root(double x) { ... }
Or change the format specifier, if you really want an int.
Following the explanation from tutorialspoint, which states, that the basic idea is to implement the Newton Raphson method for solving nonlinear equations, IMHO, the code below displays this fact more clearly. Since there is already an accepted answer, I add this answer just for future reference.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double rootCube( double a)
{
double x = a;
double y = 1.0;
const double precision = 0.0000001;
while(fabs(x-y) > precision)
{
x = (x + y) / 2.0;
y = a / x / x;
}
return x;
}
int main(int argc, const char* argv[])
{
if(argc > 1)
{
double a =
strtod(argv[1],NULL);
printf("cubeRoot(%f) = %f\n", a, rootCube(a));
}
return 0;
}
Here, in contrast to the original code of the question, it is more obvious, that x and y are the bounds, which are being improved until a sufficiently accurate solution is found.
With modification of the line in the while block, where y is being updated, this code can also be used to solve similar equations. For finding the square root, for example, this line would look like this: y = a / x.

How to create an iterative structure?

I have created some code that has multiple functions, and when an X value is entered it outputs a line that has computed the number for the given X value and h value that has been declared. However, in the terminal it only outputs one line of each value, and I need to implement some type of iterative structure that varies h from 10^-1 to 10^-8. Here is the code:
#include <stdio.h>
#include <math.h>
int main()
{
double u(double x)
{
return(pow(x,3.0));
}
double dudx(double x)
{
return(3.0 * pow(x,2.0));
}
double fdiff(double x, double h)
{
return((u(x+h) - u(x))/h);
}
double bdiff(double x, double h)
{
return((u(x) - u(x-h))/h);
}
double cdiff(double x, double h)
{
return((u(x+h)-u(x-h))/(2*h));
}
double fderr(double x, double h)
{
return(fabs(fdiff(x,h)-dudx(x)));
}
double bderr(double x, double h)
{
return(fabs(bdiff(x,h)-dudx(x)));
}
double cderr(double x, double h)
{
return(fabs(cdiff(x,h)-dudx(x)));
}
double x;
double h=1.0 * pow(10,-1.0);
printf("Enter an Integer ");
scanf("%lf",&x);
printf("u(x): %lf du/dx: %lf fd: %lf bd: %lf cd: %lf fderr: %lf bderr: %lf cderr: %lf\n", u(x), dudx(x), fdiff(x,h), bdiff(x,h), cdiff(x,h), fderr(x,h), bderr(x,h), cderr(x,h));
}
I'm pretty sure I have to use some type of for loop around this area:
double h=1.0 * pow(10,-1.0);
But, I do not know how to implement it! So to reiterate, how do I create an iterative structure that starts with an h value of 10^-1 and ends with 10^-8?
Thank you in advance!

Evaluating Taylor series expansion of e^x in C

I am very new to C programming. Here, I have written a very simple C program to evaluate the Taylor series expansion of exponential function e^x, but I am getting error in my output, though the program gets compiled successfully.
#include <stdio.h>
int main()
{
double sum;
int x;
printf("Enter the value of x: ");
scanf("%d",&x);
sum=1+x+(x^2)/2+(x^3)/6+(x^4)/24+(x^5)/120+(x^6)/720;
printf("The value of e^%d is %.3lf",x,sum);
return 0;
}
^ in C is not an exponentiation operator. It is a bitwise operator. For a short number of terms, it is easier to just multiply.
You also need to take care of integer division. If you divide x*x/2, then you will get integer division. You need to divide the number to get a double answer, as shown below.
You can replace the line calculating the sum with the following line.
sum=1+x+(x*x)/2.0+(x*x*x)/6.0+(x*x*x*x)/24.0+(x*x*x*x*x)/120.0+(x*x*x*x*x*x)/720.0;
A better option would be to use a loop to calculate each term and add it to the answer.
double answer, term = 1;
int divisor = 1;
amswer = term;
for (i=0; i<6; i++)
{
term = term * x / divisor;
answer += term;
divisor *= (i+2);
}
Use pow() instead of ^
Use double x instead of int x
So the result code will look like:
#include <stdio.h>
#include <math.h>
int main()
{
double sum;
double x;
printf("Enter the value of x: ");
scanf("%lf",&x);
sum=1+x+pow(x,2)/2+pow(x,3)/6+pow(x,4)/24+pow(x,5)/120+pow(x,6)/720;
printf("The value of e^%f is %.3lf",x,sum);
return 0;
}
It should be linked with math lib, i.e.:
gcc prog.c -lm
As other people failed to provide proper piece of C code, I have to try it:
#include <stdio.h>
int main() {
printf("Enter the value of x: ");
double x;
scanf("%lf", &x);
double sum = 1.0 + x * (1.0 + x * (1.0 / 2 + x * (1.0 / 3 + x * (1.0 / 4 + x * (1.0 / 5 + x / 6.0)))));
printf("The value of e^%.3lf is %.3lf", x, sum);
}
Better make it dynamic like this one.
#include <stdio.h>
int power(int x,int n){
int sum=1,i;
if (n == 0)
return 1;
for(i=1; i<= n; i++){
sum *= x;
}
return sum;
}
int fact(int n){
if(n == 0)
return 1;
for(i=1; i<= n; i++){
fact *=i;
}
return fact;
}
int main()
{
float sum=0.0;
int i,x,n;
printf("Enter the value of x and n terms: ");
scanf("%d %d",&x,&n);
for(i=0; i<=n; i++){
sum += (float)power(x,i)/fact(i);
}
printf("The value of %d^%d is %.3f",x,n,sum);
return 0;
}

-1.#IND00 output for certain input values

I'm trying to write a code that will take x as input and give cos(x) as output, using maclaurin's series.I'm using a while loop until the difference of two consecutive results is less then 0.001. I'm using double type to accomodate larger values.
the code works when x is in range [-2,2], but if x is greater or less than this range the ouput is -1.#IND00. Why is it happening? is the output value out of range ? how can i fix this ??
my code is :
#include <stdio.h>
double abs(double a);
double power(double p, int q);
int fact(int a);
int main()
{
int i=1,j=2*i;
double x,s=1.0,p,l=0.001;
printf("Enter x: ");
scanf("%lf", &x);
p = s+ power(-1,i) * power(x,j) / fact(j);
while (abs(p-s)>l){
i++; j=2*i;
s=p;
p = s+ power(-1,i) * power(x,j) / fact(j);
}
printf("cos(%f) = %f", x,p);
return 0;
}
double abs(double a)
{
if (a>=0) return a;
else return (-a);
}
double power(double p, int q)
{
int i;
double a=1.0;
for (i=0; i<q; i++){
a=a*p;
}
return a;
}
int fact(int a)
{
int i,p=1;
if (a==0 || a==1) return 1;
else
while (a!=1){
p=p*a;
a--;
}
return p;
}
update your scanf function to
scanf("%lf", &x);
Also you need to check pow and fact, these functions could overflow. Especially, fact which only use int.
As a larger |x| is use, more terms are needed and fact() overflows and strange results follow. Use double.
// int fact(int a)
double myfact(double p, int q) {
int i;
double a = 1.0;
for (i=0; i<q; i++){
a=a*p;
}
return a;
}
Eventually with values somewhere larger |x| > 30, other limitations kick in using this method. The limitation is due to precision and not range. For large values a significantly different algorithm should be used.
Potential conflict between int abs(int j) in <stdlib.h>. The prototyped may be found via stdio.h and conflicts with OP double abs(double a). In any case, abs() is a standard library function and OP should avoid that function name. Also recommend renaming power().
// double abs(double a)
double myabs(double a)

Resources