【发布时间】:2019-06-02 13:45:36
【问题描述】:
我正在编写一个程序,通过加倍 (link to wikihow article) 将二进制数转换为十进制数。
如果用户输入不是 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;
}
【问题讨论】:
-
改用
std::vector怎么样? -
int binArray[digitsINbinNum];不是标准 C++。 -
@JVApen 我还没学会。但是谢谢你的建议。
-
@πάνταῥεῖ 我使用的是 c++ 14,我的意思是数组的大小将由用户给出。
-
这对于 c++14 没有改变。 VLA 没有成为标准。您充其量使用的是编译器扩展。