Please help me out here; I've tried this code and it doesn't seem to work right.

1 次查看(过去 30 天)
A single positive number(256) has been given.
Add commands to use a while loop to repeatedly devide this number by 7, until the value remaining is less than 1. The code should assign values to two output variables as follows:
  • Assign the final value of the number to the output variable whatsleft.
  • Count the number of divisions required and assign the results to the output divisionCount.
This is what I tried:
number=256;
divisionCount = 0;
while number > 1
number = number / 7;
divisionCount = divisionCount + 1;
end
disp(number)
disp(divisionCount)
  3 个评论
Bongani
Bongani 2022-8-19
I do get the answers for the output, but they are not assigned to " whatsLeft and divisionCount".

请先登录,再进行评论。

回答(1 个)

Arjun
Arjun 2024-9-11
Hi,
I see that the problem statement is asking you to repeatedly divide a number and finally when it is no longer divisible store the division count and final remainder.
After looking at your code I found that it is completely correct, and you only forgot one assignment statement which is “whatsleft = number;” after the loop. Inside the while loop, you are repeatedly diving the number and each time the number reduces i.e. something is left and once the number cannot be divided you are exiting the loop hence whatever is left is stored in the variable “number” itself.
However, your solution is correct, but I would like to suggest you not to change the original variable instead you can initially take “whatsleft = number” and then perform the operations on “whatsleft” this way you can keep your original value intact for future use while achieving your goal.
Please refer to the code below:
% Number contains the original value
number=256;
% Initially whatsleft will be entire number itself
whatsleft = number;
% Initialize division count
divisionCount = 0;
% Start of the while loop
while whatsleft > 1
whatsleft = whatsleft / 7;
divisionCount = divisionCount + 1;
end
% Display all the values
disp(number)
256
disp(whatsleft)
0.7464
disp(divisionCount)
3
I hope it will help!

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by