Я кодирую программу, которая преобразует двоичное число в десятичное число путем удвоения ( ссылка на статью вики-шоу ).
Если пользовательский ввод отличается от 1 или 0, тоэто не двоичное число, в этом случае я хочу, чтобы цикл «сломался» и произнес что-то вроде:
«Упс! Двоичные числа имеют только 1 или 0».
Если не «тогда», цикл должен продолжаться.
То есть я хочу закодировать что-то вроде
for(int digits = 0; digits != digitsINbinNum; ++digits){
if(a condition that checks if user input is anything else than 1 or 0){
coût << ""Oops! Binary numbers have only 1 or 0" << endl;
break;
}else{
cin >> binArray[digits];/*<-----------Here's the part where I am trying to do that*/
}
}
Обратитесь к приведенному ниже коду для получения дополнительной информации:
#include <iostream>
#include <iterator>
using namespace std;
int main(){
int digitsINbinNum;
cout << "If you don't mind. Please enter the number of digits in your binary number: ";
cin >> digitsINbinNum;
int binArray[digitsINbinNum];
cout << "Enter the binary number: ";
for(int digits = 0; digits != digitsINbinNum; ++digits){
cin >> binArray[digits];/*<-----------Here's the part where I am trying to do that*/
}
/*using the doubling method as found in wikihow.com*/
int total = 0;
for(int posiOFdigit = 0; posiOFdigit != sizeof(binNum[noOFdigits]); posiOFdigit++){
total = total * 2 + binNum[posiOFdigit];
}
/*Printing the number*/
cout << "Decimal form of ";
for(int n = 0; n != noOFdigits; n++){
cout << binNum[n];
}
cout << " is " << total;
return 0;
}