簡體   English   中英

如果輸入確實是二進制數(只有 1 和 0),如何檢查二進制到十進制程序?

[英]How to check for a binary to decimal program if the input is indeed a binary number (only 1s and 0s)?

想編寫一個程序將二進制數轉換為十進制數,但我想確保,如果用戶輸入類似讓我們說:250 的內容,應該有一條錯誤消息並要求輸入一個真正的二進制數。

我怎么能這樣做,我真的找不到解決方案。 我已經設法阻止像“a”這樣的字符,但是這個非常棘手!

謝謝你的幫助!

我用這段代碼試過了,但是 if 語句似乎總是錯誤的,任何解釋為什么會這樣?

void isBinary(char s[MAX])

{

詮釋 i = 0; for(i = 0; i < MAX; i++)

{




    if(s[i] == 0 || s[i] == 1)

    {

        continue;


    }

    else {

        printf("Error!\n");
        break;


        }






}

}

您可以將其放入 function 中以驗證您的數據,但這看起來很簡單,如下所示:

string line;

getline(cin, line);
for (char c: line) {
    if (c != '0' && c != '1') {
        cout << "Please input binary only." << endl;
        exit(1);
    }
}

編碼

這是一個使用 C 的示例,沒有任何動態分配:

#include <stdio.h>

int main()
{
    _Bool haserror = 0;
    int result; // the number
    do
    {
        result = 0; // reset the number
        haserror = 0; // reset error
        _Bool isEmpty = 1; // this means that the user just hit enter and didn't specify any number
        char c; // we process the string character by character
        while ((c = getchar()) != '\n') // read until the newline (If you are using Windows, you might need to change this, because Windows uses "\r\n" for newlines)
        {
            isEmpty = 0; // there is some imput

            if (c != '0' && c != '1')
            {
                printf("This is unacceptable!\n");
                while (getchar() != '\n'); // clear out the garbage

                haserror = 1; // there's an error, loop
                break;
            }

            result <<= 1; // the actual conversion from binary to decimal, using advanced binary operations
            result |= (c - '0');
        }

        if (isEmpty)
        {
            printf("Nothing is unacceptable, too!\n");
            haserror = 1;
        }
    } while (haserror); // loop until there isn't any error

    printf("%d\n", result);
}

這缺少一些功能(Windows 換行符、 EOF處理),但顯示了主要邏輯。

數學

假設我們已經讀取了數字1010 ,並且需要將數字1添加到末尾。 我們需要為新數字創造空間,所以我們將它向左移動一。

Before: 1010
After:  10100

然后我們用(c - '0')得到實際數字。 如果c'0' ,則'0' - '0'0 如果c'1' ,那么它在 ASCII 中的值為49 ,減去 '0' 的值,即 ASCII 中的48 49 - 48 = 1 ,所以'1'將被轉換為1 ,這是正確的。

然后我們或它。

10100 OR
00001
-----
10101

不好的答案

#include <stdio.h>
#include <stdlib.h>

_Bool validate(const char * c);

int main()
{
    char buffer[10]; // very ugly fixed-size buffer
    while (1)
    {
        if (scanf("%9s", buffer) == EOF) // EOF means reading error, propably not recoverable
            return 1;

        while ((readError = getchar()) != '\n' && readError != EOF); // clear out the garbage
        if (readError == EOF) // there is no more data to read
            return 1;
        if (!validate(buffer)) // main work is done via strtoul(), but it returns 0 on error, so there isn't any way to distinguish bad imput from user typing 0, so we need to check manually
        {
            printf("This is unacceptable!\n");
            continue;
        }
        printf("%ld\n", strtoul(buffer, 0, 2)); // strtoul converts the string to unsigned long
        break;
    }
}

_Bool validate(const char * c)
{
    for (; *c != 0; c++) // iterate through all character, checking if they're '0' or '1'
    {
        if (*c != '0' && *c != '1')
            return 0;
    }
    return 1;
}

此代碼處理數據 3 次( scanf()讀取數據, validate()驗證數據, strtoul()提取數字)。 我的其他解決方案更長但更好。

這次我添加了EOF檢查。

同樣,Windows 換行符可能會出現一些並發症。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM