MATLAB Answers

What is the code that converts decimal to octal without using the built-in functions?

34 ビュー (過去 30 日間)
miraa basil
miraa basil 2018 年 11 月 1 日
編集済み: Walter Roberson 2018 年 11 月 4 日
What is the code that converts decimal to octal without using the built-in functions

  0 件のコメント

サインインしてコメントする。

回答 (2 件)

Elias Gule
Elias Gule 2018 年 11 月 1 日
The following code is neither elegant nor memory efficient, but it appears to address your question:
function output = dec2octal(num)
output = '';
while num >= 8
fact = floor(num / 8);
num = mod(num,8);
output = [output num2str(fact)]; %#ok<AGROW>
end
output = [output num2str(num)];
end

  3 件のコメント

Walter Roberson
Walter Roberson 2018 年 11 月 1 日
>= and floor and mod and / and [] and num2str are all built in functions and so cannot be used for this purpose.
Elias Gule
Elias Gule 2018 年 11 月 1 日
I don't think he wanted to take it that far... remember English is not our first language. I think he probably wanted to understand how the decimal to octal logic could be implemented in Matlab.
miraa basil
miraa basil 2018 年 11 月 3 日
It doesnt give the right answer, it should convert from decimal to octal using your code but the answer doesnt meet.

サインインしてコメントする。


Walter Roberson
Walter Roberson 2018 年 11 月 1 日
編集済み: Walter Roberson 2018 年 11 月 4 日

  1 件のコメント

Walter Roberson
Walter Roberson 2018 年 11 月 4 日
Algorithm:
if input is negative, error
if input is 0, emit '0' and return
initialize output to ''
assign input to a variable
while the variable is greater than 0 do
take mod8 of the variable
convert the mod8 to character, and put that at the beginning of the output
subtract the mod8 from the variable and divide by 8, and assign that result to the variable
end of loop

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by