简体   繁体   English

在c中检查给定数字是否为二进制

[英]check given number is binary or not in c

#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;
}

This code is working perfectly fine for non binary numbers and for binary number when I run it in first attempt, but when I trie to input a binary number in the second attempt, it interpreted binary number as non binary.当我第一次尝试运行它时,此代码对于非二进制数和二进制数工作得非常好,但是当我尝试在第二次尝试中输入一个二进制数时,它将二进制数解释为非二进制数。

I am stuck at this step.我卡在这一步。

Output shows输出显示

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:

As said using main() for a recursive routine is not the best idea, you might aswell make a separate function to do the same thing without that pesky main() recursive call.如前所述,将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现场样品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM