gpt4 book ai didi

c - printf 奇怪的字符

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:21 25 4
gpt4 key购买 nike

为什么它不起作用?在程序的最后,它显示了 2 个奇怪的字符,而不是“e primo”或“nao e primo”。如果你能帮助我,我将不胜感激。

#include <stdio.h>
#include <stdlib.h>

int main() {
// var
int n, c = 2;
char p[11];
// code
printf("Informe um numero para checar se e primo: ");
scanf("%d", &n);
do {
if (n % c == 0) {
p[11] = 'e primo';
break;
} else {
p[11] = 'nao e primo';
}
c = c + 1;
} while (c != n / 2);
printf("\nO numero %s", p);
return 0;
}

最佳答案

你的程序有一些问题:

  • 您不能使用简单赋值 p[11] = 'e primo'; 复制字符串。如果您使缓冲区变大,则可以将 strcpy() 与字符串一起使用,或者您可以只使用字符串指针 const char *p;

  • 如果 n 小于 4,循环将永远运行。更准确地说,当 c = c + 1; 导致算术溢出时,它会调用未定义的行为。

  • 结果与其他值完全相反。

  • 对于大素数,循环很慢,当 c * c > n 时应该停止。

这是更正后的版本:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
// var
int n, c;
const char *p = "e primo";
// code
printf("Informe um numero para checar se e primo: ");
if (scanf("%d", &n) == 1) {
for (c = 2; c * c <= n; c = c + 1) {
if (n % c == 0) {
p = "nao e primo";
break;
}
}
printf("O numero %s\n", p);
return 0;
}

关于c - printf 奇怪的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40577532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com