Question:
How to write a Matlab code which successively halves a number (>=1; positive), entered by the user until the result is less than 1. The program should print out the first number, and then the values each time it is successively halved.
Answer:
The probelm can be solved using while loop. The code is given below:
clear all; clc; close all a = input('Enter a positive number greater than 1: '); i = 1; fprintf('#\tsuccessive Division\n') while a > 2 a_half = a/2; a = a_half; fprintf('%d\t\t%f\n',i,a_half) i = i + 1; end disp('The number is less than 1')
OUTPUT
Enter a positive number greater than 1: 119 # successive Division 1 59.500000 2 29.750000 3 14.875000 4 7.437500 5 3.718750 6 1.859375 The number is less than 1
0 Comments