|
|
| Autor |
Nachricht |
der_Pate4 Newbie


Anmeldungsdatum: 08.06.2012 Beiträge: 1
|
Verfasst am: 08 Jun 2012 - 22:30:41 Titel: C# - Primzahlenberechnung |
|
|
wollte ein C# programm schreiben wo man eine Zahl eingibt und dann geprüft wird ob diese eine Primzahl ist... so weit so gut... das Problem: wenn es keine Primzahl ist bekomm ich keine Antwort in der Console. '?
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x;
for(int i =1;i>0;i++)
{
Console.WriteLine("Geben Sie eine Zahl zum Prüfen ein: ");
x = Convert.ToInt32(Console.ReadLine());
if (x == 0)
return;
Prim(x);
if (Prim(x) == true)
{
Console.WriteLine(x + " ist eine Primzahl!");
}
else
{
Console.WriteLine(x + " ist KEINE Primzahl!");
}
}
Console.ReadLine();
return;
}
static bool Prim(int x)
{
bool pz = true;
for (int i = 2; i <= x - 1; )
{
if (x % i == 0)
{
pz = false;
}
else
{
i++;
}
}
return pz;
}
}
} |
|
 |
a1 Full Member


 Anmeldungsdatum: 21.06.2011 Beiträge: 209
|
Verfasst am: 08 Jun 2012 - 22:59:36 Titel: |
|
|
Hallo,
deine Methode zur Prüfung einer Primzahl verrennt sich in einer Endlosschleife bei Eingabe einer Nicht-Primzahl.
Ändert die Methode so und schon gehts:
| Code: |
static bool Prim(int x)
{
bool pz = true;
for (int i = 2; i <= x - 1; i++)
{
if (x % i == 0)
{
pz = false;
}
}
return pz;
}
|
Gruß
a1 _________________ Es gibt 10 Arten von Menschen. Die, die Binär verstehen und die, die es nicht verstehen. |
|
 |
|