A02.m - Period of a Pendulum
% Tidy up the workspace clc % clear command window clear % clear all variables close all % close all graphics windows g = 9.8; % define acceleration of gravity in MKS units % prompt user to enter the length of a pendulum L = input('Enter length of pendulum (in meters): '); % calculate the period P = 2*pi*sqrt(L/g); % the first fprintf statement prints a blank line to space things out. % the second fprintf statement prints the period of the pendulum in command % window and specifies that 3 sig figs should be displayed. fprintf('\n') fprintf('Period = %.3g seconds\n',P)
This program demonstrates how to prompt the user for information and how to display quantitative results in a controlled way using fprintf. The fprintf command is common to many programming languages including C and C++. It provides a way of controlling the number of significant digits displayed and whether the number is written in scientific notation or not. The first argument of the fprintf() command is a string that controls the fomatting of the displayed number. See the examples below to see how this works. The \n character adds a carriage return so the next print statement starts on a new line. Try monkeying around with these examples
- fprintf('%.3f',pi) - prints pi to 3 decimal places (3.142)
- fprintf('%.5f',pi) - prints pi to 5 decimal places (3.14159)
- fprintf('%.3f',1000*pi) - prints 1000*pi to 3 decimal places (3141.593)
- fprintf('%.3e',pi) - prints pi to 3 decimal places using scientific notation(3.142e+00)
- fprintf('%.3e',1000*pi) - prints 1000*pi to 3 decimal places using scientific notation(3.142e+03)
- fprintf('%.3g',pi) - prints pi to 3 sig figs (3.14)
- fprintf('%.3g',1000*pi) - prints 1000*pi to 3 sig figs (3.14e+03)
- fprintf('%i',4) - prints an integer