
Available under Creative Commons-ShareAlike 4.0 International License.
Using a while loop, calculate for
using an increment of
.
This time we need to initialize the x value outside the loop and then state the test condition in the first line of the while loop. We also need to create an increment statement within the while loop:
x=-pi; while x<=pi y=cos(x); fprintf('%8.3f %8.2f nn',x,y); x = x + (pi/4); end
The result is the same as that of the previous example:
-3.142 -1.00 -2.356 -0.71 -1.571 0.00 -0.785 0.71 0.000 1.00 0.785 0.71 1.571 0.00 2.356 -0.71 3.142 -1.00
Now we can improve the code by adding extra formatting lines and comments:
clear; clc; fprintf(' x cos(x)nn') % title row fprintf(' ----------------nn') % title row x=-pi; % initiating the x value while x<=pi % stating the test condition y=cos(x); % calculating the value of y fprintf('%8.3f %8.2f nn',x,y); % printing a and y x = x + (pi/4); % iterating to the next step end
The result should look the same as before.
x cos(x) ---------------- -3.142 -1.00 -2.356 -0.71 -1.571 0.00 -0.785 0.71 0.000 1.00 0.785 0.71 1.571 0.00 2.356 -0.71 3.142 -1.00
- 瀏覽次數:1389