【问题标题】:check given number is binary or not in c在c中检查给定数字是否为二进制
【发布时间】:2020-06-27 15:59:00
【问题描述】:
#include <stdio.h>

void binarytodecimal(int n);


int main() {

    int num;
    printf("Input a binary number: ");
    scanf("%d", &num);

    int copy = num, temp = 0;

    while(copy != 0) {
        temp = copy%10;

        if((temp==0) || (temp==1)) {
            copy = copy/10;
            if(copy == 0) {
                printf("valid binary number.\n");
                break;
            }
        }
        else {
            printf("Not a valid binary number. Try again\n");
            main();
        }

    }

    return 0;
}

当我第一次尝试运行该代码时,该代码对于非二进制数和二进制数都可以正常工作,但是当我在第二次尝试中尝试输入二进制数时,它将二进制数解释为非二进制数。

我卡在这一步了。

输出显示

Input a binary number: 122
Not a valid binary number. Try again
Input a binary number: 101
valid binary number.
Not a valid binary number. Try again
Input a binary number:

【问题讨论】:

  • 首先:在这里使用recusion(从main 调用main)是一个非常糟糕的主意。
  • @Yksisarvinen -- 在 C 中可以,在 C++ 中不行。
  • @Yksisarvinen 在 C 中是允许的,但这并不意味着这是一个好主意。我见过的所有代码,要么是有趣的代码,要么是设计不佳的代码。
  • 二进制、十进制、八进制、十六进制等都是以文本形式表示值的方式。只有当您想将文本转换为值或将值转换为文本时,您才关心文本表示使用的基础;值无关紧要。
  • @Sanjay Singh 是您对“二进制数”的定义:十进制表示仅包含数字“1”和“0”的数字

标签: c algorithm binary


【解决方案1】:

正如所说的将main() 用于递归例程并不是最好的主意,您不妨创建一个单独的函数来执行相同的操作,而无需那个讨厌的main() 递归调用。

#include <stdio.h>

void check_binary(int *num) {
    int copy, temp = 0;
    printf("Input a binary number: ");
    scanf("%d", num);
    copy = *num;

    while (copy != 0) {
        temp = copy % 10;

        if ((temp == 0) || (temp == 1)) {
            copy = copy / 10;
            if (copy == 0)
            {
                printf("valid binary number.\n");
                break;
            }
        }
        else {
            printf("Not a valid binary number. Try again\n");
            check_binary(num);
            break;
        }
    }
}

int main() {
    int num; //variable will be saved for future use
    check_binary(&num);
    return 0;
}

Live sample

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2022-01-13
    • 1970-01-01
    • 2020-12-11
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多