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!