C语言程序:检查数字是否属于特定进制
给定一个表示数字的字符串和一个进制;任务是检查给定的数字是否属于该进制。
我们需要根据数字系统检查数字和进制,其中进制包括:二进制为2,八进制为8,十进制为10,十六进制为16。根据此,我们需要找到给定的字符串数字是否属于特定进制。如果属于特定进制,则在输出屏幕上打印“Yes”;否则打印“No”。
例如,我们知道数字/表达式“1A6”是16进制,“1010”是2进制,但这可以通过简单的视觉分析判断,现在我们需要找到一种方法来通过程序解决这个问题。
示例
Input: str = “1010”, base =2 Output: yes Input: str = “1AA4”, base = 16 Output: yes Input: str = “1610”, base = 2 Output: No
我们将使用的解决问题的方法 −
- 检查进制是否在2到16之间。
- 然后检查字符串的每个数字是否属于特定进制。
- 如果属于,则返回true,否则返回false。
算法
Start
Step 1 -> In function bool isInGivenBase(char str[], int base)
If base > 16 then,
Return 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,
Return false
Else
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,
Return false
Return true
Step 2 -> In function int main()
Set str[] = {"AF87"}
If isInGivenBase(str, 16) then,
Print "yes "
Else
Print "No "
Stop示例
#include <ctype.h>
#include <stdio.h>
#include <string.h>
bool isInGivenBase(char str[], int base) {
// Allowed bases are till 16 (Hexadecimal)
if (base > 16)
return false;
// If base is below or equal to 10, then all
// digits should be from 0 to 9.
else if (base <= 10) {
for (int i = 0; i < strlen(str); i++)
if (!(str[i] >= '0' and
str[i] < ('0' + base)))
return false;
}
// If base is below or equal to 16, then all
// digits should be from 0 to 9 or from '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;
}
// Driver code
int main() {
char str[] = {"AF87"};
if (isInGivenBase(str, 16))
printf("yes
");
else
printf("No
");
return 0;
}输出
yes
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP