using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
int c;
for (a = 2; a < 100;a++ )
{
for (b = 2; b < a;b++ )
{
c = 1;
if (a % b == 0)
{
c = 0;
break;
} }
if (c == 1) {
Console.WriteLine(a);
}
}
}
}
}
提示我C是局部变量,有错误
int b = 0;
int c = 0;
{
static void Main(string[] args)
{
for (int a = 2; a < 100;a++ )
{
bool prime = true; for (int b = 2; b * b < a;b++ )
{
if (a % b == 0)
{
prime = false;
break;
} }
if (prime) {
Console.WriteLine(a);
}
}
}
}局部变量未赋值
//看你的代码中有 using System.Linq;
//写了个linq的DEMO
void Main()
{
Enumerable.Range(1,100).ToList().ForEach(n=>Console.Write(primeNumber(n)?n.ToString()+" ":" "));
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
}
bool primeNumber(int n)
{
bool b=true;
if(n<2) b=false;
else if(n==2){
b=true;
}
else
{
for(int i=2;i<=(int)Math.Sqrt(n);i++)
{
if(n%i==0)
{
b=false;
break;
}
}
}
return b;
}
#include <stdio.h>
#include <math.h>
void main()
{ int n=0, i, j,w,k;
for(i=2;i<=1000; i++)
{
w=1;
k=sqrt(i); //开平方根
for (j=2; j<=k; j++)
if (i%j==0) { w=0; break; }
if (w)
{
++n;
if (n%10==0) printf("%d\n",i);
else printf("%d\t",i);
}
}
}
就可以了
只需要给int c 随便赋个值就行了,声明变量跟初始化变量是不一样的
{
if((i==2)||(i==3)||(i==5)||(i==7))
{
console.writeline(i);
continue; }
if(i%2==0)
{
continue;
}
if(i%5==0)
{
continue;
}
if(i%3==0)
{
continue;
}
if(i%7==0)
{
continue;
}
console.writeLine(i);
}
2、里面的循环到Math.Sqrt(n)就可以了,这样可以提高效率见#4
只作int i;
不会分配内存空间的。
赋值的时候分配了内存空间,但是要考虑可访问性,或者变量声明周期的问题。