我是初學者。我應該寫一個簡單的原始分解程式,我想出的東西有一個奇怪的行為。輸入應該在 64 位整數(long long)范圍內。
它作業得很好,直到我輸入特定長度的值,即 13。(附圖片),在這種情況下,它只是關閉而沒有錯誤,我認為這表明程式將數字視為 0,因為否則它應該給出錯誤.
現在,我認為問題可能出在指標或 scanf 函式中,所以如果有人指出我的錯誤所在,我將不勝感激。我在 Windows 10 上的 VS 中編程,使用標準命令提示符作為終端。
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
#include<stdint.h>
int ReadInput(int64_t *n, int *ret);
void Primal_Factorization(int64_t n);
enum {INPUT_ERROR = 100, SUCCESS = 0};
int main()
{
int ret = SUCCESS;
int64_t n = 0;
while (ReadInput(&n, &ret) > 0)
{
Primal_Factorization(n);
}
if (n < 0)
{
fprintf(stderr, "Error: Chybny vstup!\n");
ret = INPUT_ERROR;
}
return ret;
}
int ReadInput(int64_t *n, int *ret){
if(scanf("%lld", n) != 1){
*n = 0;
fprintf(stderr, "Error: Chybny vstup!\n");
*ret = INPUT_ERROR;
}
return *n;
}
void Primal_Factorization(int64_t n){
int64_t n_sqrt = sqrt(n);
int count;
int64_t n_origin = n;
bool first_iteration = true;
printf("Prvociselny rozklad cisla %lld je:\n", n);
for (int i = 2; i <= n_sqrt; i ){
count = 0;
if(n % i == 0){
if(first_iteration == false) printf(" x ");
while (n % i == 0){
n = n / i;
count ;
}
if(count != 1) printf("%d^%d", i, count);
else printf("%d", i);
first_iteration = false;
} else continue;
}
if(n_origin == n) printf("%lld\n", n);
else if(n != 1) printf(" x %lld\n", n);
else printf("\n");
}

uj5u.com熱心網友回復:
在這個函式中:
int ReadInput(int64_t *n, int *ret){
if(scanf("%lld", n) != 1){
*n = 0;
fprintf(stderr, "Error: Chybny vstup!\n");
*ret = INPUT_ERROR;
}
return *n;
}
64 位整數作為 an 回傳,int然后在main()函式中用于檢查該值是否為正。的范圍int取決于系統,但如果int是 32 位(非常常見的情況),那么例如 10^18 將在截斷為 32 位后得到值-1486618624,即負值。因此,程式終止是因為 from 的回傳值ReadInput()是負數,但它不會列印錯誤,因為n(未截斷的 64 位整數)是正數。
最小的修改是ReadInput()回傳一個int64_t而不是int:
int64_t ReadInput(int64_t *n, int *ret)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/341541.html
