2016-11-13 77 views
1

为什么它不起作用?在节目结束时,它显示2个奇怪的字符,而不是“e primo”或“nao e primo”。如果你能帮助我,我将不胜感激。Printf奇怪的字符

#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; 
} 
+1

这并不编译: “在恒定太多的字符” 在线'P [11] = 'E的Primo';'等 –

回答

1

你的程序有一些问题:

  • 你不能用一个简单的任务p[11] = 'e primo';复制串。如果将缓冲区设置得更大,或者可以使用字符串指针​​,则可以使用strcpy()和一个字符串。

  • 如果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; 
    } 
+0

为什么当我们在数组中使用char时,我们做出如下归因:C [10] ='hello',当我们使用指针时,我们这样做:C =“hello”为什么我们在第一个上使用'''持续?不是两个字符串? – Gibas

+0

@Gibas:'C [10] ='hello''是一个语法错误(或不应该使用的过时的多字符字符常量)。它们可以用来初始化数组:'char C [10] =“e primo”;'或者在上下文中它们衰减为指针初始化的初始字符的指针: 'char * p =“e primo”;'和指针赋值:'p =“nao e primo”;' – chqrlie

+0

我利用了错误的例子,我的意思是你不能使用c =“j”,但你可以使用char C [10] =“e primo”如果是单个字符或字符串,是否需要不同的符号? – Gibas

1

数组中没有第12个元素;他们只有p中的11个元素。因此您的任务(p[11] = 'e primo';)因此导致undefined behaviour

'e primo'是一个多字节字符字面值,具有实现定义的行为。您可能需要使用strcpy()进行复制。

strcpy(p, "e primo"); 

(并增加数组大小以适应在注释中指出的其他字符串副本中的较长字符串)。

或者,您可以简单地使用指向字符串文字的指针,因为哟并不需要该数组。

char *p = "nao e primo"; 
printf("Informe um numero para checar se e primo: "); 
scanf("%d", &n); 
do { 
    if (n % c == 0) { 
     p = "e primo"; 
     break; 
    } else { 
     p = "nao e primo"; 
    ... 

printf("\nO numero %s", p); 

相关:Single quotes vs. double quotes in C or C++

+0

。 ..并增加'char p [11]的大小;'以适应'nao e primo''。 –

0

首先,你不能说

p[11] = 'e primo'; 

p是字符的阵列,并用对[11]可以设置或检索第11位的字符。其次,索引11没有字符。在C中,索引从0开始,所以你可以在p [0],p [1],...,p [10]中检索字符。 11个要素。

您是否阅读过警告?

1.c: In function ‘main’: 
1.c:16:21: warning: character constant too long for its type 
      p[11] = 'e primo'; 
        ^
1.c:16:21: warning: overflow in implicit constant conversion [-Woverflow] 
1.c:21:21: warning: character constant too long for its type 
      p[11] = 'nao e primo'; 
        ^
1.c:21:21: warning: overflow in implicit constant conversion [-Woverflow] 

它实际上是说character constant too long for its type

,你能说什么:

p[10] = 'e' 

然后,与%s您打印 “字符串”:有确定的0确定字符的阵列。 因此,在最后一个字符应该是可见的后,你必须说,例如: p [10] ='\ 0'。

我会使代码工作,但我不确定实际上是什么点。看起来,你总是把最后一个字符分配给某个东西。

+0

奇怪的字符是关于没有**'\ 0'**作为最后一个字符。当分配** char * p =“某个常量字符串”**时,C会执行此操作。 –