C语言页码计算程序报错Process terminated with status -1073741510求助
问题分析与修复方案
首先,你的程序崩溃(错误码 -1073741510,对应Windows系统中进程因无限循环耗尽资源被终止)主要是两个变量相关的低级错误导致的,再加上当前算法效率极低的问题,具体拆解如下:
1. 直接引发崩溃的核心错误
变量未初始化
在no_of_pages函数中,long no_digits_page;这个变量没有被初始化,第一次进入循环时它的值是内存里的随机垃圾值,会导致后续的位数判断完全混乱,甚至让no_digits无法正常递减,直接陷入无限循环。
变量名拼写错误
代码里有一个分支写的是:
else if(no_digits_pages == 5)
但你定义的统计单页位数的变量是no_digits_page(单数形式),这里写成了复数no_digits_pages,导致当页码是5位数时,这个分支永远不会被触发,no_digits不会减去5,循环会一直跑下去,最终被系统强制终止。
2. 算法效率问题(次要但必须优化)
当前你采用逐页计算每个页码位数的逻辑,当no_digits是百万级别的数值时,这个循环要执行几百万甚至上千万次,完全没必要。我们可以利用数学规律批量计算:
- 1位数页码:1-9,共9个,总位数
9*1=9 - 2位数页码:10-99,共90个,总位数
90*2=180 - 3位数页码:100-999,共900个,总位数
900*3=2700 - ...以此类推,n位数页码有
9*10^(n-1)个,总位数9*10^(n-1)*n
修复后的代码
修复变量错误的原逻辑版本(可正常运行,但效率低)
#include <stdio.h> #include <stdlib.h> #include <time.h> // 计算页码数的函数 long no_of_pages(long no_digits) { long no_pages = 0; while(no_digits > 0) { no_pages++; // 统计页码数 long aux = no_pages; long no_digits_page = 0; // 初始化变量!统计单页的位数 while(aux) { aux = aux / 10; no_digits_page++; } if(no_digits_page == 1) no_digits--; else if(no_digits_page == 2) no_digits -= 2; else if(no_digits_page == 3) no_digits -= 3; else if(no_digits_page == 4) no_digits -= 4; else if(no_digits_page == 5) // 修复变量名拼写错误 no_digits -= 5; else if(no_digits_page == 6) no_digits -= 6; else if(no_digits_page == 7) no_digits -= 7; else if(no_digits_page == 8) no_digits -= 8; else if(no_digits_page == 9) no_digits -= 9; } if (no_digits < 0) { return no_pages - 1; } else return no_pages; } int main() { long no_pages, no_digits; srand(time(0)); no_digits = (rand() % 10000000) + 10000; printf("The number of digits are %ld\n", no_digits); no_pages = no_of_pages(no_digits); printf("The number of pages are %ld\n", no_pages); return 0; }
高效优化版本(批量计算,无循环浪费)
#include <stdio.h> #include <stdlib.h> #include <time.h> long no_of_pages(long no_digits) { long pages = 0; long digit_count = 1; // 当前处理的页码位数 long start = 1; // 当前位数的起始页码 long end = 9; // 当前位数的结束页码 while (no_digits > 0) { long total_digits_this_group = (end - start + 1) * digit_count; if (no_digits >= total_digits_this_group) { // 完全包含当前位数的所有页码 pages += (end - start + 1); no_digits -= total_digits_this_group; // 进入下一位数的页码范围 digit_count++; start *= 10; end = end * 10 + 9; } else { // 只能包含当前位数的部分页码 pages += no_digits / digit_count; no_digits = 0; } } return pages; } int main() { long no_pages, no_digits; srand(time(0)); no_digits = (rand() % 10000000) + 10000; printf("The number of digits are %ld\n", no_digits); no_pages = no_of_pages(no_digits); printf("The number of pages are %ld\n", no_pages); return 0; }
验证说明
- 修复变量错误后,原逻辑就能正常运行,但对于大的
no_digits值会运行很慢; - 优化后的版本用批量计算的方式,无论
no_digits多大,都只需要循环最多9次(对应1-9位数页码),效率提升几个数量级。
内容的提问来源于stack exchange,提问作者rucarr
相关产品推荐
相关产品推荐

