C语言循环内m值变为0 进制转换代码无法读取用户输入如何修改
问题根因
- 字符数组长度定义不足导致栈溢出:你定义的
char n[8]仅能存储7个有效字符+1个字符串结束符\0,当输入8位长度的进制串时,scanf写入的结束符会越界覆盖栈上相邻的变量m的内存空间,因此出现m变为0的异常。 scanf读取字符串的写法不规范:数组名本身就是首地址指针,不需要额外加取地址符&,错误写法也可能引发内存操作异常。
修复代码
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int m, i=0, a=0, q; char n[9]; // 修改:长度改为9,容纳8位有效字符+1位结束符 scanf("%d", &m); scanf("%8s", n); // 修改:去掉&,加长度限制避免溢出 while (i<8){ q=n[i]-'0'; a+=(int)(pow(m, 7-i)+0.5)*q; i++; } printf("%d", a); return 0; }
可选优化(非必须)
pow是浮点运算函数,计算整数幂时可能存在精度误差,你可以用整数累乘的方式替换,避免精度问题同时提升性能,无需再引入math.h:
#include <stdio.h> #include <stdlib.h> int main() { int m, i=0, a=0, q, weight = 1; char n[9]; scanf("%d", &m); scanf("%8s", n); // 从最低位开始计算 for(i=7;i>=0;i--){ q = n[i] - '0'; a += q * weight; weight *= m; } printf("%d", a); return 0; }
内容的提问来源于stack exchange,提问作者Adrenno
相关产品推荐
相关产品推荐

