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

Programme C vérifie si un nombre appartient à une base spécifique

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

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

As we know, the number/The expression “ 1A6,16 1010,2, but this can be judged by intuitive analysis, now we must find a way to solve the problem. Program.

Exemple

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 in2To16Between.

  • 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
Étape 1 -> In function bool isInGivenBase(char str[], int base)
   If base > 16 then,
      Retourner false
   Else If base <= 10 then,
   Boucle pour i = 0 et i < strlen(str) et i++
      If !(str[i] >= '0' and str[i] < ('0 + then,
         Retourner false
      Sinon
      Boucle pour i = 0 et i < strlen(str) et i++
         Si PAS ((str[i] >= '0' && str[i] < ('0' + base)) ||
            (str[i] >= 'A' && str[i] < ('A' + base - 10) ) alors,
            Retourner false
            Retourner true
   Étape 2 -> Dans la fonction int main()
      Définir str[] = {"AF",87"});
      Si isInGivenBase(str, 16) alors,
         Imprimer "Oui"
      Sinon
         Imprimer "Non"
Arrêt

Exemple

#include <ctype.h>
#include <stdio.h>
#include <string.h>
bool isInGivenBase(char str[], int base) {
   //Les bases autorisées sont16(hexadécimal)
   if (base > 16))
      return false;
      //Si la base est inférieure ou égale à10Alors
      // Le nombre de digits doit être entre 0 et9。
   else if (base <= 10)) {
      for (int i = 0; i < strlen(str); i++))
      if (!(str[i] >= '0' and
         str[i] < ('0' + base)))
         return false;
   }
   //Si la base est inférieure ou égale à16Alors
   //Le nombre doit être entre 0 et9ou '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))
      ))
      return false;
   }
   return true;
}
// Code du pilote
int main() {
   char str[] = {"AF",87"});
   if (isInGivenBase(str, 16))
      printf("yes\n");
   else
      printf("No\n");
   return 0;
}

Résultat de la sortie

oui