学习型 ASP/PHP/ASP.NET 主机 30元/年全能 ASP/PHP/ASP.NET 主机,支持月付专业 MSSQL 数据库空间,支持月付专业 MySQL 数据库空间,支持月付
发新话题
打印

提个问各位大虾请帮忙解答下

提个问各位大虾请帮忙解答下

题目要求是让程序显示1到10之间质数的个数 可我做好后编译显示结果总是不对请帮我看下错在哪
代码如下
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication21
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j, k, a;
            //i=个数 j=循环量 k计数器 a结果


            k = 0;
            for (i = 1; i <= 10; i++)
            {

                for (j = 2; j <= i - 1; j++)
                {
                    if ((i % j )== 0)
                    {
                        k=k+1;
                        break;
                    }
                    Console.WriteLine("num the SUM {0}", i);
                    a = i - k - 2;
                    Console.WriteLine("num is zhishu {0}", a);
                    Console.ReadLine();


编译后显示
i=3
a=1
狂汗不知道错哪了

TOP

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //i是代表质数,sum是代表质数的和
            int sum = 0;
            for (int i=1; i<=10; i++)
            {
                //flag是用来判断的,如果i%j的数有为零的说明不是质数,记号为true
                bool flag = false;
                for (int j = 2; j <= Math.Sqrt(i) + 1; j++)
                {
                    if (i % j == 0)
                    {
                        flag = true;
                    }

                }
                if (i == 2 || flag == false)
                {
                   sum++;
                    Console.WriteLine(i);
                  
                }
               
            }
            Console.WriteLine("1到10的质数个数为:"+sum);
            Console.ReadLine();
        }
    }
}
如果还有什么不懂的可以回复

TOP

for (int j = 2; j <= Math.Sqrt(i) + 1; j++)
这句是为了算法的执行速度会快些,for (int j = 2; j <i; j++)代替。
说一下你的错误 for (j = 2; j <= i - 1; j++)
你的i是从1起的  j <= i - 1表示j<=0才执行下面的
显然是不可能的  所以不会执行for里面代码

TOP

发新话题