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 个评论
Voss
2022-8-19
After the while loop:
whatsLeft = number;
Looks like you have divisionCount already.
回答(1 个)
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)
disp(whatsleft)
disp(divisionCount)
I hope it will help!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!