【发布时间】:2021-10-28 15:38:13
【问题描述】:
我是初学者。我应该写一个简单的原始分解程序,我想出的东西有一个奇怪的行为。 输入应该在 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");
}
【问题讨论】:
-
return *n;是int ReadInput()的错误类型。函数值也应该是int64_t。但它不应该代表输入的成功吗? 值是通过一个参数。并且成功与int *ret重复。 -
哦,这也很重要...谢谢!从现在开始我也会关注它。好吧,程序也应该在用户输入 0 时结束,这就是我采用该逻辑的原因。并不是说我觉得它优越,这只是我能想到的唯一方法。
-
我将函数定义简化为
int ReadInput(int64_t *n)并返回成功状态。 -
我明白了!非常感谢您的建议,我觉得这样的东西对于初学者来说至关重要!
-
有
#include <inttypes.h>定义的宏可用于为int64_t构造scanf和printf格式说明符:scanf("%" SCNd64, n)(n是int64_t*),printf("%" PRId64 "\n", n)(n是int64_t)。请注意,这些使用字符串文字连接。SCNd64和PRId64可能会扩展为"lld"(如果int64_t与您的平台上的long long int相同),因此"%" PCId64可能会扩展为"%" "lld",这是由于字符串文字连接与"%lld"相同。
标签: c prime-factoring