【问题标题】:How to check if a binary number contains digits different from 0 and 1 in c?如何检查二进制数是否包含与c中的0和1不同的数字?
【发布时间】:2020-06-17 00:47:41
【问题描述】:

我想写一个函数,提示用户输入 bin_num 二进制序列 0-s 和 1-s 和 输出以下内容。

A) bin_num 的十进制表示

B) bin_num 的十六进制表示(以 16 为底)

如果输入无效(即,如果 bin_num 包含不同于 0 和 1 的数字),用户应该 收到一条错误消息(详情如下)。

程序运行示例:

Please enter binary number input: 112011

invalid input, please try again.

Please enter binary number input: 110011

110011 to decimal is: 51

110011 to hexadecimal is: 0x33

为了正确解决问题,我将无法将二进制数读取为 整数,因为它可能会导致溢出。 另一方面,答案(十进制)将始终符合标准整数大小。

我的问题是如何检查二进制数是否包含不同于 0 和 1 的数字?

这是我的代码:

#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define ENTERING_QUESTION "Please choose a question by entering 1-5 (enter 0 to exit):" 


#define MAX_SIZE_INPUT 31
#define QUESTION1_INPUT_MESSAGE "Please enter binary number input:"
#define QUESTION1_OUTPUT_MESSAGE_DECIMAL "to decimal is:"
#define QUESTION1_OUTPUT_MESSAGE_HEXADECIMAL "to hexadecimal is:"
#define QUESTION1_ERROR_MESSAGE "invalid input, please try again."
void bin2hexanddec(char *bin_str)
{
    char *ptr;
    long long input_num= strtol(bin_str, &ptr, 10);
    int dec = 0, i = 0, rem;
    
    while (input_num != 0) {
        rem = input_num % 10;
        input_num /= 10;
        dec += rem * pow(2, i);
        ++i;
    }
    printf("%lld " QUESTION1_OUTPUT_MESSAGE_DECIMAL " %d\n", input_num, dec);
    printf("%lld " QUESTION1_OUTPUT_MESSAGE_DECIMAL " %X\n", input_num, dec);

    return;

}

.
.
.
int main()
{

    char bin_str[MAX_SIZE_INPUT
    .
    .
    .
    printf(ENTERING_QUESTION"\n");
    scanf("%d", &choice);
        if (choice == 1) {
            printf(QUESTION1_INPUT_MESSAGE"\n");
            scanf("%s", bin_str);
            bin2hexanddec(bin_str);
        }
    .
    .
    .


    return 0;
}

【问题讨论】:

  • 我很确定没有二进制数包含除 0 或 1 以外的其他数字 :) 那么您在这里实际问的是什么,如何清理用户输入字符串?
  • 你可以写一个检查函数来接受用户输入,看看是否只有01存在并相应地给出错误
  • 我从用户那里得到二进制数,我需要检查输入的正确性。 @Lundin
  • scanf("%s", bin_str); 你输入了一个字符串。现在:检查此字符串是否包含除“0”和“1”以外的其他字符。祝你好运!
  • 可以用strspn检查字符串中是否有除'0''1'以外的字符。

标签: c


【解决方案1】:

这很简单。

int isbinary(const char *str)  //zero if OK non zero if not OK
{
    while(*str && (*str == '0' || *str == '1')) str++;
    return *str;
}

int main(void)
{
    printf("%s\n",isbinary("101100001011") ? "NOT OK" : "OK");
    printf("%s\n",isbinary("101100e01011") ? "NOT OK" : "OK");
}

如果您希望非零也可以,只需将 return *str; 更改为 return !*str;

https://godbolt.org/z/6nq-TC

你的转换算法没有太大意义。

unsigned long long convert(const char *str)
{
    unsigned long long result = 0;

    while(*str)
    {
        result <<= 1;
        result += *str++ == '1';
    }
    return result;
}

https://godbolt.org/z/_KQR4f

【讨论】:

    猜你喜欢
    • 2020-10-06
    • 2018-09-19
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多