我想檢查變數 "num "是什么,從0-15 我如何檢查它是否是這些數字中的一個,以及它是什么數字,到目前為止我已經得到了。
#include <iostream>
使用 命名空間 std.com.cn>。
int num = 0;
int main()
{
cout << "要檢查的數字:"。
Cin >> num;
{
if num = 0;
cout << "0000";
{
if num = 2;
cout << "0010";
{
if num = 1;
cout << "0001";
{
if num = 3;
cout << "0011";
{
if num = 4;
cout << "0100";
{
if num = 7;
cout << "0111";
{
if num = 5;
cout << "0101";
{
if num = 6;
cout << "0110";
{
if num = 8;
cout << "1000";
{
if num = 9;
cout << "1001";
{
if num = 10;
cout << "1010";
{
if num = 11;
cout << "1011";
{
if num = 12;
cout << "1100";
{
if num = 13;
cout << "1101";
{
if num = 14;
cout << "1110";
{
if num = 15;
cout << "1111";
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return 0;
我怎樣才能做到這一點,如果我做不到,我怎樣才能將一個數字轉換為一個4位的二進制位元組?如果可能的話,我怎樣才能確保輸入的數字在0-15的范圍內,并且輸入的字串中沒有字母呢
uj5u.com熱心網友回復:
下面的程式做了你想要的事情。
int main() {
int num = 0;
std::cout << "要檢查的數字。"。
std::cin >> num;
while (std::cin.fail() || num > 15 || num < 0) {
std::cout << "錯誤! 無效輸入
"。
std::cin.clear()。
std::cin.ignore(256, '
')。
std::cout << "要檢查的數字。"。
std::cin >> num;
}
std::bitset<4> value。
value = { static_cast<unsigned long> (num) };
std::cout << value.to_string() << "
"。
return 0;
uj5u.com熱心網友回復:
使用<bitset>
。#include < bitset>
#include <iostream>
#include <string>
int main()
{
std::string input{ "12" }。
//std::cin >> input;
unsigned long number = std::stoul(input); //做數字檢查。
if (number < 16) //做值檢查。
{
std::bitset<4> value{ number };
std::cout << value.to_string() << std::endl;
}
uj5u.com熱心網友回復:
由于你將num宣告為一個整數,如果你在cin期間輸入非數字字符,你的程式將無法作業。我相信在不處理std::bitset的情況下,你的代碼的最短變體將是
const int MAX_BITS = 4;
cout << " Number to check:";
cin >> num;
if (num < 0 || num > (1 < < MAX_BITS) - 1) {
cout << "無效數字,下次輸入0和" << (1 << MAX_BITS) - 1;
return 0;
}
for(int bit = MAX_BITS - 1; bit >= 0; -bit){
cout << ((num & (1 << bit)) > 0) 。
}
cout << endl;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/326076.html
標籤:
上一篇:MQTT 基本知識簡介
