首页 > 试题广场 >

编写一个控制台应用程序,要求完成下列功能。 1)&n

[问答题]

编写一个控制台应用程序,要求完成下列功能。

1)   接收一个整数 n。

2)   如果接收的值 n 为正数,输出 1 到 n 间的全部整数。

3)   如果接收的值为负值,用 break 或者 return 退出程序。

4)   转到(1)继续接收下一个整数。

class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("请输入一个整数:");
                bool flag = int.TryParse(Console.ReadLine(), out int n);
                if (flag)
                {
                    if (n > 0)
                    {
                        for (int i = 1; i <= n; i++)
                        {
                            Console.Write(i + " ");
                        }
                        Console.WriteLine();
                    }
                    else if (n < 0) 
                    {
                        Console.WriteLine("输入的是负数,程序结束!");
                        break;
                    }
                }
                else
                {
                    Console.WriteLine("无输入,程序结束!");
                    return;
                }
            }
        }
    }

编辑于 2019-09-20 09:29:41 回复(0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo5
{
    class Program
    {
        static void Main(string[] args)
        {
            string num = "";            
            int snum;
            Console.WriteLine("Please input an integer:");
            while (true)
            {
                string str = "";
                num = Console.ReadLine();
                if (int.TryParse(num, out snum))
                {
                    if (snum > 0)
                    {
                        for (int i = 1; i <= snum; i++)
                        {
                            str += i.ToString() + " ";
                        }
                    }
                    else if (snum == 0)
                    {
                        Console.WriteLine("If you enter 0,it can't output values");
                        continue;
                    }
                    else
                    {
                        return;
                    }
                    Console.WriteLine(str);
                }
                else
                {
                    Console.WriteLine("Please input an integer!");
                    continue;
                }
            }
        }
    }
}
发表于 2018-11-21 14:24:02 回复(0)