简体   繁体   English

C程序:仅使用数组检查输入的数字是1和0

[英]C program: Checking digits entered are 1s and 0s only using arrays

So I am trying to make a smaller simple program to solve a problem. 所以我试图制作一个更小的简单程序来解决问题。 For this, I am trying to check to make sure the user inputs a number containing ONLY 1s and 0s and then I will use this number to perform a division. 为此,我试图检查以确保用户输入一个仅包含1和0的数字,然后我将使用此数字执行除法。 For example the number 11010 or 10111. Now my problem is, if I declare an integer to store this number (as follows) there wouldn't be a way to check all the digits are 1s or 0s right? 例如,数字11010或10111.现在我的问题是,如果我声明一个整数来存储这个数字(如下所示),那么就没有办法检查所有数字是1还是0对吗?

int userInput;

Now, I can use an array for this. 现在,我可以使用一个数组。 (I know how to do this BUT this leads to my second problem.). (我知道如何做到这一点,但这导致了我的第二个问题。) Like so: 像这样:

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

int main (int argc, char *argv[]){
    int myArray[20];
    int i, input, length;
    printf("Please enter how long your number is: \n");
    scanf("%d", &length);
    for (i = 0; i < length; i++){
        printf("Please enter digit %d of your array\n", i+1);
        scanf("%d", &input);
        assert ((input == 1) || (input ==0));


    }

For example, for the first digit the user enters a '1', the second digit the user enters a '0', then the third digit the user enters '0'. 例如,对于第一个数字,用户输入“1”,用户输入“0”的第二个数字,然后用户输入“0”的第三个数字。 I need to "grab" this number though. 我需要“抓住”这个数字。 How would I grab this number "100" and perform arithmetic operations on it. 我如何获取此数字“100”并对其执行算术运算。 I hope this makes sense, if not moderators please give me a chance to clear it up. 我希望这是有道理的,如果不是主持人,请给我一个机会清理它。

EDIT: Many have suggested the modulo approach. 编辑:许多人提出了模数方法。 BUT I still want to know if I can do this with an array. 但是我仍然想知道我是否可以用数组做到这一点。 That is creating a integer variable and set that equal to each element the user has entered in the array. 这是创建一个整数变量,并设置为等于用户在数组中输入的每个元素。

You don't really need to get the number one digit at a time. 你真的不需要一次获得一位数。

It is easy to extract the digits of an int. 很容易提取int的数字。 Notice that a number such as 12345 is actually 5 * 10^0 + 4 * 10^1 + 3 * 10^2 + 2 * 10^3 + 1 * 10^4. 请注意,12345之类的数字实际上是5 * 10 ^ 0 + 4 * 10 ^ 1 + 3 * 10 ^ 2 + 2 * 10 ^ 3 + 1 * 10 ^ 4。

To get the lowest digit you can just take the remainder of the number when divided by 10 (ie mod it by 10 using the % operator). 要获得最低位数,您可以在除以10时使用数字的余数(即使用%运算符将其修改为10)。 So, 12345 % 10 is 5. To get the next digit, you can divide the number by 10 (getting 1234) and then mod by ten again - giving you 4. Keep doing this as long as you have digits left in the number (ie the number is > 0). 所以,12345%10是5.要获得下一个数字,你可以将数字除以10(得到1234)然后再将10除以 - 给你4.只要你的数字中有数字,就继续这样做(即数字> 0)。

#include <stdio.h>


int is_valid(int number) {
  if (number == 0) return 1; // its a 0.
  while (number != 0) {
    int digit = number % 10;
    if (digit != 1 && digit != 0) return 0;
    number = number / 10;
  }
  return 1; // no other digits were found.
}

int main() {
  int n;
  scanf("%d", &n);
  if (is_valid(n)) printf("valid\n");
  else printf("not valid\n");
  return 0;
}

Here's another idea: 这是另一个想法:

Just write the number again into a string. 只需将数字再次写入字符串即可。 Then iterate over the string checking each character. 然后迭代检查每个字符的字符串。 This is somewhat less efficient, but simpler to understand/code. 这样效率稍差,但理解/编码更简单。

#include <stdio.h>

int is_valid(int n) {
  char buffer[20];
  char *c;
  sprintf(buffer, "%d", n);
  for(c = buffer; *c != '\0'; c++) {
    if (*c != '0' && *c != '1') return 0;
  }
  return 1;
}

int main() {
  int n;
  scanf("%d", &n);
  if (is_valid(n)) printf("valid\n");
  else printf("not valid\n");
  return 0;
}

EDIT: Since you mentioned in your edit that you are not interested in alternate approaches and just need a way to "grab" the digits as they are fed in, I'm adding this to my answer. 编辑:因为你在编辑中提到你对替代方法不感兴趣,只需要一种方法来“抓住”数字,因为它们被输入,我将这个添加到我的答案中。

Keep a variable initially set to 0. Now as each digit comes in, (I am assuming the user enters higher digits before lower ones), we multiply our variable by 10 and add the new digit to it. 保持变量初始设置为0.现在每个数字进入,(我假设用户在较低的数字之前输入更高的数字),我们将变量乘以10并将新数字添加到它。 Thus, if the user enters 1, 0, 0, our variable is initially 0, the its 1 (0 * 10 + 1), then its 10 (1*10 + 0) and finally 100 (10 * 10 + 0), which is what we needed. 因此,如果用户输入1,0,0,我们的变量最初是0,其1(0 * 10 + 1),然后是10(1 * 10 + 0),最后是100(10 * 10 + 0),这就是我们需要的。

I think this could be more simple: 我认为这可能更简单:

bool is_zeros_and_ones(int n) {
  for (; n != 0; n /= 10) {
    int mod = n % 10;
    if (0 != mod && 1 != mod) {
      return false;
  }
  return true;
}

So you can input whole number and test it without arrays. 因此,您可以输入整数并在没有数组的情况下测试它。

You don't need an array to store all the digits. 您不需要数组来存储所有数字。

Keep dividing by 10 & taking modulo to get each digit & keep a single flag to mark if all digits are 1 or 0. 保持除以10并取模数得到每个数字并保留一个标记,如果所有数字都是1或0则标记。

Of course works only for max word size of the integer... 当然只适用于整数的最大字大小...

Something like: 就像是:

char isBinary = 1;

int copyInput = +input;

while(copyInput  && (isBinary=copyInput%10<=1)) copyInput/=10;

Maybe something like this would be enough 也许这样的事情就足够了

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

int main (int argc, char *argv[]){
    int myArray[21];
    printf("Please enter your number (max 20 digits)\n");
    scanf("%s", myArray);
    for (i = 0; i < strlen(myArray); i++){
        assert ((myArray[i] == 1) || (myArray[i] == 0));
    }

You could cheat your way by making sure the program always deals with ints. 你可以通过确保程序始终处理整数来欺骗你的方式。 Your array basically holds the binary representation of a base 10 number. 您的数组基本上保存基数为10的二进制表示。 Why not use it convert to an int . 为什么不使用它转换为int Then you can apply all operations to that number just as you would operate on ints . 然后,您可以像对ints操作一样将所有操作应用于该数字。

Here is what i mean 这就是我的意思

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

int main (int argc, char *argv[]){
    int i, input, length;
    int num = 0; /* holds the actual number */


    printf("Please enter how long your number is <= %d: \n", 8 * sizeof(num) - 1);
    scanf("%d", &length);
    for (i = 0; i < length; i++){
        printf("Please enter digit %d of your array\n", i+1);
        scanf("%d", &input);
        assert ((input == 1) || (input ==0));
        /* humans enter numbers L TO R */
        /* set that bit if it is one */
        num |= (input << (length - i - 1)) ;
    }

    printf("Your number in base 10 is %d\n",num); 
    /* Now you do normal multiplications, additions, divisions */
    /* The only thing remaining now is to convert from base 10 to base 2. */
}

Sample run
Please enter how long your number is <= 31: 
5
Please enter digit 1 of your array
1
Please enter digit 2 of your array
1
Please enter digit 3 of your array
1
Please enter digit 4 of your array
1
Please enter digit 5 of your array
0
Your number in base 10 is 30

This solution is only for the second part of the problem. 此解决方案仅适用于问题的第二部分。 You can take the input as characters and use atoi to convert them to integer. 您可以将输入作为字符并使用atoi将它们转换为整数。

char arrayOfNumbers[MAX_LENGTH];
char tmpChar;
int number;
for (i = 0; i < length; i++){
    printf("Please enter digit %d of your array\n", i+1);
    scanf("%c", &tmpChar);
    assert ((tmpChar == '1') || (tmpChar == '0'));
    arrayOfNumbers[i] = tmpChar;
}

/*make sure it is NULL terminated*/
arrayOfNumbers[length] = '\0';
number = atoi(arrayOfNumbers);

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

相关问题 如果输入确实是二进制数(只有 1 和 0),如何检查二进制到十进制程序? - How to check for a binary to decimal program if the input is indeed a binary number (only 1s and 0s)? C-遍历0和1的数组,就像二进制数字一样 - C - iterate over array of 0s & 1s as if binary number 使用类型转换将 char 转换为 int 会使 C 中的 1 变为 49 和 0 变为 48? - Converting char to int using typecasting makes 1s into 49 and 0s into 48 in C? 我正在编写代码以找出总数之间的差异。 二进制数中的 1 和 0,使用 Arrays - I am writing a code to find out the difference between the total no. of 1s and 0s in a binary number, using Arrays 0和1的数组组合 - Array combinations of 0s and 1s 用 1 和 0 填充矩阵以满足给定的行和列总和的程序 - Program to fill a matrix with 1s and 0s to such that it satisfies the given row and column sums 如何将 32 位整数的位模式存储在 C 中的 32 长度的 0 和 1 字符串中 - How to store the bit pattern of a 32 bit integer in a 32 length string of 0s and 1s in C 如何生成随机0和1,但在C中出现的可能性为80-20? - How to generate random 0s and 1s but with 80-20 probability of their occurence in C? 如何从 C 中的 1 和 0 数组中获取十六进制数? - How to obtain a hex number from an array of 1s and 0s in C? 位向量到0和1的整数向量 - Bit Vector to Integer vectors of 0s and 1s
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM