English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C программа для проверки, принадлежит ли число определенной基数

Given number as a string and base; the task is to check if the given number is a given base.

We must check the number and base according to the number system, where there are 2 binary numbers, 8 octal numbers, 10 decimal numbers, and 16 hexadecimal numbers. According to this, we must find out if the given number in the string belongs to a specific base, if it belongs to a specific base, then it must be printed on the output screen 'Yes'; otherwise, 'No' is displayed on the output screen.

As we know, the number/expression '1A6' has a base of 16, and '1010' has a base of 2, but this can be judged by intuition, now we must find a way to solve this problem. Program.

Пример

Input: str = '1010', base = 2
Output: yes
Input: str = '1AA4', base = 16
Output: yes
Input: str = '1610', base = 2
Output: No

The method we will use to solve the given problem-

  • Check if the base is between 2 and 16.

  • Then check each digit of the string to see if it belongs to a specific base.

  • If it belongs, return true, otherwise return false.

Algorithm

Start
Step 1 -> In function bool isInGivenBase(char str[], int base)
   If base > 16 then,
      Возврат false
   Else If base <= 10 then,
   Loop For i = 0 and i < strlen(str) and i++
      If !(str[i] >= '0' and str[i] < ('0' + base)) then,
         Возврат false
      Иначе
      Loop For i = 0 and i < strlen(str) and i++
         If NOT ((str[i] >= '0' && str[i] < ('0' + base)) ||
            (str[i] >= 'A' && str[i] < ('A' + base - 10)) then,
            Возврат false
            Возврат true
   Шаг 2 -> В функции int main()
      Установить str[] = {"AF87"}
      Если isInGivenBase(str, 16) то,
         Вывод "yes "
      Иначе
         Вывод "No "
Стоп

Пример

#include <ctype.h>
#include <stdio.h>
#include <string.h>
bool isInGivenBase(char str[], int base) {
   // Допустимое основание 16 (шестнадцатеричное)
   if (base > 16)
      возврат false;
      // Если основание не превышает 10, то все
      // Разряды должны быть от 0 до 9.
   else if (base <= 10) {
      for (int i = 0; i < strlen(str); i++)
      if (!(str[i] >= '0' and
         str[i] < ('0' + base)))
         возврат false;
   }
   // Если основание не превышает 16, то все
   // Число должно быть от 0 до 9 или 'A'
   else {
      for (int i = 0; i < strlen(str); i++)
      if (! ((str[i] >= '0' &&
         str[i] < ('0' + base)) ||
         (str[i] >= 'A' &&
         str[i] < ('A' + base - 10))
      ))
      возврат false;
   }
   возврат true;
}
// Код драйвера
int main() {
   char str[] = {"AF87"};
   if (isInGivenBase(str, 16))
      printf("yes\n");
   else
      printf("No\n");
   возврат 0;
}

Результат вывода

да
Основной учебник
Рекомендуется к просмотру