Classwork 5: Functions

Objectives

To practice using functions in the math library and to write a simple function of your own.

The Assignment

Part 1


Write a program that calculates the fifth root of a number that the user types in. A sample run of your program might look like this:


PT[116]% gcc -Wall fifth.c -lm

PT[117]% ./a.out
This program calculates the fifth root.
Enter x: 243
The fifth root of 243.000000 is 3.000000.

PT[118]% ./a.out
This program calculates the fifth root.
Enter x: 300
The fifth root of 300.000000 is 3.129135.

PT[119]% ./a.out
This program calculates the fifth root.
Enter x: 3500
The fifth root of 3500.000000 is 5.114623.

PT[120]% 

To calculate the fifth root, use the pow() function from the math library. To do so, you must have the following preprocessor directive at the top of your program:

   #include <math.h>

The function call pow(x,y) returns the value of x raised to power y. For example, pow(4,3) returns 64 and pow(16, 0.5) returns 4. See the math.c program as an example.

Note: the expression 1/5 evaluates to 0 because it is an integer divided by an integer, so the division is integer division. Use 1.0/5.0 or 0.2.

Name your program fifth.c, compile it using the -lm options:

gcc -Wall fifth.c -lm

You need the -lm flag to tell gcc to use the math library.


Part 2


Make a copy of your fifth.c file and call the new file fifth2.c.

For version 2 of your assignment, create a function that computes the fifth root of a number. Call this function fifth_rt. Your fifth_rt function should not print anything to the screen or ask the user for input. (See example functions from class notes.) It should take one double value for input (its "formal parameter") and return the fifth root of that value.

Modify your main program so it uses your own fifth_rt() function instead of calling pow() from the math library. The sample runs of your program should look the same as before.

What to submit

Use the script command to record yourself compiling and running the first and second version of your program. Run each version 3 times with different inputs. Exit from script. Finally, submit both versions of your program and the typescript file

submit cs104_chang cw05 fifth.c fifth2.c typescript


Be sure to logout completely when you have finished!