如何用C语言基础语法提取指定序数位数字并计算其平方?
解决方法
首先,你需要先处理负数的情况——计算位数和提取数字时都应该用n的绝对值,因为数字的位数和正负无关。另外,log10()对负数会产生未定义行为,必须先取绝对值。
接下来,提取从左往右第c位数字的核心思路是:
- 确定需要将原数除以的10的幂次:比如数字2451(4位),要取第2位,就除以
10^(4-2)=100得到24,再对10取模得到4。 - 为了避免
pow()函数的浮点数精度问题(比如pow(10,3)可能返回999.999999而非1000),可以用if/else if枚举所有可能的位数(因为n的范围是(-1000000,1000000),最多6位),直接计算除数,完全符合你不能使用循环、数组、字符串的限制。
完整代码
#include <stdio.h> #include <stdlib.h> // 用于abs()函数 int main() { int n, c, d, count; int num; // 存储n的绝对值 printf("Enter number: "); scanf("%d", &n); // 检查n的范围 if (n <= -1000000 || n >= 1000000) { printf("Wrong entry!"); return 1; } num = abs(n); // 计算数字的位数 if (num == 0) { count = 1; } else if (num < 10) { count = 1; } else if (num < 100) { count = 2; } else if (num < 1000) { count = 3; } else if (num < 10000) { count = 4; } else if (num < 100000) { count = 5; } else { // num < 1000000 count = 6; } printf("Choose the ordinal digit you want to find the square of: "); scanf("%d", &c); // 检查c的范围 if (c < 1 || c > count) { printf("Wrong digit!"); return 1; } // 提取第c位数字 int divisor; if (count == 1) { divisor = 1; } else if (count == 2) { divisor = (c == 1) ? 10 : 1; } else if (count == 3) { if (c == 1) { divisor = 100; } else if (c == 2) { divisor = 10; } else { divisor = 1; } } else if (count == 4) { if (c == 1) { divisor = 1000; } else if (c == 2) { divisor = 100; } else if (c == 3) { divisor = 10; } else { divisor = 1; } } else if (count == 5) { if (c == 1) { divisor = 10000; } else if (c == 2) { divisor = 1000; } else if (c == 3) { divisor = 100; } else if (c == 4) { divisor = 10; } else { divisor = 1; } } else { // count ==6 if (c == 1) { divisor = 100000; } else if (c == 2) { divisor = 10000; } else if (c == 3) { divisor = 1000; } else if (c == 4) { divisor = 100; } else if (c == 5) { divisor = 10; } else { divisor = 1; } } d = (num / divisor) % 10; int square = d * d; // 输出结果 printf("The chosen ordinal digit is %d, its square is %d.\n", d, square); return 0; }
代码说明
- 负数处理:用
abs()函数获取n的绝对值,确保位数计算和数字提取不受符号影响。 - 位数计算:通过
if/else if枚举所有可能的位数,避免了log10()的浮点数精度问题和对负数的未定义行为。 - 数字提取:通过分支判断确定除数,再用
(num / divisor) %10得到目标数字,完全符合限制条件。 - 结果输出:计算目标数字的平方并按要求格式输出。
测试你的示例输入:
Enter number: 2451
Choose the ordinal digit you want to find the square of: 2
The chosen ordinal digit is 4, its square is 16.
运行代码后会得到符合要求的输出。
内容的提问来源于stack exchange,提问作者Mambaaa824
相关产品推荐
相关产品推荐

