2016-08-14 3 views
-6
#include <stdio.h> 
#include <conio.h> 

void main() { 
    int a, n, x; 
    clrscr(); 
    printf("enter a number"); 
    scanf("%d", &a); 
    n > 1; 
    a != n && n < a; 
    if (a/n == x) 
     printf("a is not a prime no"); 
    else 
     printf("a is a prime no"); 
} 

Wenn ich dies ausführe und eine zusammengesetzte Zahl setze, zeigt es immer noch als Primzahl.Was ist mit diesem Code falsch? (um zu überprüfen, ob eine gegebene Zahl eine Primzahl ist)

+3

Diese Zeilen nichts zu tun: 'n> 1;' und 'a = n &&n SurvivalMachine

+1

Haben Sie nicht vergessen, sagen Sie, eine Schleife in dort? 'n' und' x' sind nicht einmal initialisiert. Informieren Sie sich über 'for'-Schleifen und, naja, über grundlegende C im Allgemeinen. Dein Code macht absolut keinen Sinn, obwohl ich denke, dass du irgendeine Art von Schleife willst, aber nicht weißt wie oder was. Mit anderen Worten: ** lerne zuerst ein paar grundlegende C **. –

Antwort

1

Ihre if Aussage ist nie wahr Duo zu n und x sind nicht initialisiert. Deshalb bekommst du nur dein anderes als Rückkehr. Außerdem gibt Ihr Ausdruck n>1; und a != n && n < a; einen Bool zurück, der zu nichts gezwungen wird. In diesem Fall müssen Sie eine for Schleife verwenden.

Hier a link über for-Schleife

int main() 
{ 
    int a,n,x = 0; 

    printf("enter a number: "); 
    scanf("%d",&a); 
    for(n=2; n<=a/2; ++n) 
    { 
     if(a%n==0) 
     { 
      x=1; 
      break; 
     } 
    } 
    if (x==0) 
     printf("",n); 
    else 
     printf("a is not a prime no");  
    return 0; 
} 
+0

auch wenn wir i deklarieren, kommt die Ausgabe (wenn ich irgendeine Nr. Eintippe) nicht. – ash22

-1
#include<stdio.h> 
#include<conio.h> 
int main() 
{ 
    clrscr();//clearing the screen 
    int n,x=2,count=0;//Here count is initialised to 0,if it is not prime it remains the same,else it will be equal to 1.You will understand this as you go down 
    //A number is a prime number if it is not divisible by any other number from 2 and the number before it. 
    printf("Enter a number : "); 
    scanf("%d",&n); 
    while(x<n)//As this checking process should continue till the number just preceding it 
    { 
     if(n%x==0)//checking if the number n is divisible by x or not 
     { 
      count++;//IF divisible,there is no meaning in continuing,So we are coming out of the loop by incrementing the variable "count" 
      break; 
     } 
     else 
     x++; 
    } 
    if(count==0) 
    { 
     printf("%d is a prime number",n); 
     return 0;//Here if number is prime,There is no need to go further and execute till end,To reduce time complexity ,We will write a return statement to stop executing the code. 
    } 
    printf("%d is not a prime number",n); 
    return 0; 

} 
Verwandte Themen