|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
今天在网上看到一段分解质因数的代码,想自己试试,于是抄了过来,自己玩了一下,果然,玩脱了。。
- #include <stdio.h>
- #include <stdlib.h>
- #include <malloc.h>
- int main() {
- int inputNum = 0, j = 0;
- printf("Please input a NUMBER to decomposed prime factor: ");
- scanf("%d", &inputNum);
- printf("The prime factors are: ");
- const int leng = 1;
- int *result = (int *)malloc(leng * sizeof(int));
- int i = 2;
- int result_idx = 0;
- while (i * i <= inputNum) {
- while (inputNum % i == 0) {
- result[result_idx] = i;
- inputNum /= i;
- result_idx++;
- }
- i++;
- }
- if (inputNum > 1) {
- result[result_idx] = inputNum;
- }
- while (j <= result_idx) {
- printf("%d\t", result[j]);
- j++;
- }
- return 0;
- }
复制代码
最后一个 while,括号里如果是 “j <= result_idx”,那么在 scanf 的地方输入 1024,就会多出一个未分配的地址。。但是如果改成 “j < result_idx”,输入 74 或者 82 这样的数,质因数又不会完全显示。。如下图。。
求各位大佬帮忙掌掌眼,看看我这是哪里弄错了。。
本帖最后由 jackz007 于 2022-7-25 00:24 编辑
- const int leng = 1 ;
- int * result = (int *)malloc(leng * sizeof(int)) ; // result 只分配了 1 个元素空间,就是说,只有 result[0] 可以存入 1 个整型数。
- . . . . . .
- result[result_idx] = i ; // result 只有保存一个整数的能力,却被当成一维整型数组,用于保存多个元素,必然导致下标越界。
复制代码
下面是我写的代码,可以不用一维数组
- #include <stdio.h>
- int main(void)
- {
- int c , k , n ;
- printf("Please input a NUMBER to decomposed prime factor : ") ;
- scanf("%d" , & n) ;
- printf("The prime factors are : ") ;
- for(c = 0 , k = 2 ; k * k < n + 1 ; k ++) {
- for(; ! (n % k) && (k * k < n + 1) ; n /= k , c ++) {
- if(c) printf("\t") ;
- printf("%d" , k) ;
- } ;
- }
- if(c) printf("\t") ;
- printf("%d\n" , n) ;
- }
复制代码
编译、运行实况:
- D:\[00.Exerciese.2022]\C>g++ -o x x.c
- D:\[00.Exerciese.2022]\C>x
- Please input a NUMBER to decomposed prime factor : 1024
- The prime factors are : 2 2 2 2 2 2 2
- 2 2 2
- D:\[00.Exerciese.2022]\C>
复制代码
|
|