c++ to matlab
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Faisal Al-Wazir
am 7 Mär. 2022
Bearbeitet: Walter Roberson
am 8 Mär. 2022
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 Kommentar
Walter Roberson
am 8 Mär. 2022
Your assignment requires that you create a flowchart first and work from that.
Akzeptierte Antwort
Image Analyst
am 8 Mär. 2022
You'll learn more if you do it yourself than if someone else does it for you. Here are some tips:
- Get rid of the first 4 lines of your code.
- Get rid of any { that starts a block of statements.
- Replace any } that ends a block of statements with "end"
- Replace comment starter // with %.
- Replace string binary="" with binary=""
- Replace exit(0) with return;
- Replace "length=binary.length()" with "bLength = length(binary)"
- 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 Kommentare
Image Analyst
am 8 Mär. 2022
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!