c++ to matlab

2 次查看(过去 30 天)
Faisal Al-Wazir
Faisal Al-Wazir 2022-3-7
i need somone to convert c++ to matlab
#include<iostream>
using namespace std;
main(){
int num,length,n;
cout<<"Please enter a number between 0 and 255: ";
cin>> num; // Taking input
n=num; //Copy of input number for operations so that input number is stored intact
if(num>255 || num<0){ // Validating range
cout<<"Number out of range";
exit(0);
}
string binary=""; // Initializing Null (empty) String
while(n>0){ // Process of converting decimal to binary
binary=to_string(n%2)+binary; // Concatenating Strings (each new bit in front of other bits)
n=n/2;
}
length=binary.length(); // If length of binary is less than 8 then convert add trailing zeros in front
if(length<8){
for(int i=length+1;i<=8;i++)
binary="0"+binary;
}
cout<<"The binary equivalent of "<<num<<" is "<<binary;
}
  1 个评论
Walter Roberson
Walter Roberson 2022-3-8
Your assignment requires that you create a flowchart first and work from that.

请先登录,再进行评论。

采纳的回答

Image Analyst
Image Analyst 2022-3-8
You'll learn more if you do it yourself than if someone else does it for you. Here are some tips:
  1. Get rid of the first 4 lines of your code.
  2. Get rid of any { that starts a block of statements.
  3. Replace any } that ends a block of statements with "end"
  4. Replace comment starter // with %.
  5. Replace string binary="" with binary=""
  6. Replace exit(0) with return;
  7. Replace "length=binary.length()" with "bLength = length(binary)"
  8. Replace "for(int i=length+1;i<=8;i++)" with "for i = bLength+1 : 8"
Handle remaining errors as you encounter them. Post resulting code that you can't fix here.
  4 个评论
Image Analyst
Image Analyst 2022-3-8
Two hours -- that will be plenty of time. I'm sure you're not allowed to turn in my work as your own anyway. Here's a start (almost 90% done for you):
num = input("Please enter a number between 0 and 255: ");
n=num; %Copy of input number for operations so that input number is stored intact
if(num>255 || num<0) % Validating range
uiwait(errordlg("Number out of range"));
return;
end
binary=""; % Initializing Null (empty) String
loopCounter = 1;
maxIterations = 1000;
while(n>0) && loopCounter < maxIterations % Process of converting decimal to binary
binary = to_string(n%2)+binary; % Concatenating Strings (each new bit in front of other bits)
n=n/2;
loopCounter = loopCounter + 1;
end
bLength = length(binary); % If length of binary is less than 8 then convert add trailing zeros in front
if (bLength < 8)
for i= bLength + 1 : 8
binary="0" + binary;
end
fprintf("The binary equivalent of %d is %s\n", num, binary);
end
See if you can finish it.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by