c#問題(拜託請用c#回答 不要用c++或c語言)
1. 請依據底下說明來設計一個程式:
(1) 定義一個method: prime(int n) 用來判斷n是否為質數,若是質數傳回true,否則傳 回f alse。
(2)在主程式中,由鍵盤輸入一個界限值x,請應用prime method來印出小於x的所有質數,並計算共有多少個質數。
2. 請依據底下說明來設計一個程式:
(1) 定義一個method: reverse(string s) 用來將字串s反轉。
(2) 在主程式中,由鍵盤輸入一個字串,請應用reverse method印出反轉後的字串。
1 個解答
- prisoner26535Lv 71 0 年前最佳解答
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Prime
{
class Program
{ // for problem (2) ---- to reverse a string
static string reverse(string s) { // returns a reversed string
string x = null;
for (int hi = s.Length - 1; hi >= 0; --hi) x+=s[hi];
return x;
}
// for problem (1) ---- to check if a number is prime?
static bool primex(int n) // returns if a positive number is prime or not
{
for (int i = (int) Math.Sqrt((double)n+1.0f); i > 1; --i) if (0 == n % i) return false;
return true;
}
static void Main(string[] args)
{ // ============ problem (1) ======================================
Console.Write("Enter a positive number: ");
int x = Convert.ToInt32(Console.ReadLine());
int c; // the counter
int n; // the loop index
for (n = 2, c = 0; n <= x; ++n) if (primex(n)) ++c;
Console.WriteLine("Between 2 and " + x + ", there are " + c + " prime numbers.\n");
// ============ problem (2) ======================================
Console.Write("Enter a string & I will reverse it: ");
string a = Console.ReadLine();
Console.WriteLine("Reverse of " + a + " is " + reverse(a));
Console.ReadLine();
return;
}
}
}