c - 我如何计算在 C 中不使用 /10 的数字中的位数?
问题描述
我需要以二进制编码的十进制数计算位数,例如 00111001。我不能使用典型的 /10,因为它会卡在 2 个最后一个 0 上并且不计算它们。
#include <stdio.h>
#include <stdlib.h>
void main(void) {
int bcd, digits;
printf("Input BCD number: ");
scanf_s("%d", &bcd);
for (digits = 0; (bcd / 10) != 0; digits++)
bcd /= 10;
printf("Number of digits is %d", digits+1);
getchar;
}
因此,如果我输入 1111 它显示“4”是正确的,但是当我输入 0011 时它显示“2”,那么我该如何解决呢?
解决方案
当我输入 0011 时,它显示“2”,那么我该如何解决呢?
用于"%n"
记录扫描的偏移量。
int n1;
int n2;
if (scanf_s(" %n%d%n", &bcd, &n1, &n2) == 1) {
printf("Input %d\nNumber of digits is %d\n", bcd, n2 - n1);
}
推荐阅读
- javascript - 使用 useRef 获取高度和宽度会给我 TypeError
- python - 尝试从opencv中的hevc(h265)视频读取帧时“找不到起始编号(以文件名)”
- rust - 解析带有逗号分隔数据的文本文件时出现 ParseIntError?
- python - 如何获取从同一父类扩展的类中的属性
- azure-devops - AzureDevOps - 发布管道中的缓存任务
- angular - 如何更改primeng日历中的“今天”按钮标签
- amazon-s3 - 用于将文件从 Amazon EMR 上的 HDFS 移动到 Spark 应用程序的 Amazon S3 的任何 AWS S3 API
- javascript - 如何正确更改 *ngFor 项目的样式?
- javascript - 如何在 Google Colab 中使用 Svelte
- c - 在 C 中,如何创建一个函数,给定一个字符串文字作为参数,返回一个 char*?(没有在堆上分配新内存)