[C#] Tính tổng các số nguyên tố và sắp xếp giảm của các số chẵn
Viết chương trình nhập vào 1 mảng với 0<=n<=100.
Hãy:
+ Nhập chữ T: Tính tổng các số nguyên tố.
+ Nhập G: Sắp xếp giảm của các số chẵn
Sử dụng phương thức.
Phần mềm: Visual studio
CODE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication3 { class Program { static public int n; static public int[] a = new int[100]; public static void nhap_mang() { Console.Write("Nhap n:"); n = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < n; i++) { Console.Write("Nhap phan tu thu {0}: ", +i); a[i] = Convert.ToInt32(Console.ReadLine()); } } public static void xuat_mang() { Console.Write("Day so vua nhap:"); for (int i = 0; i < n; i++) { Console.Write(a[i]); Console.Write(" "); } Console.WriteLine(); } public static int tong_so_nguyen_to() { int tong = 0; for (int i = 0; i < n; i++) { if (songuyento(a[i])) tong += a[i]; } return tong; } public static Boolean songuyento(int n) { bool check = true; if (n == 1 || n == 2) return true; for (int i = 2; i < n; i++) if (n % i == 0) check = false; if (check) return true; else return false; } public static void sap_xep_mang_so_chan() { for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (a[j] > a[i]) { int tg = a[i]; a[i] = a[j]; a[j] = tg; } Console.WriteLine("Day so chan giam dan:"); for (int i = 0; i < n; i++) { if (a[i] % 2 == 0) { Console.Write(a[i]); Console.Write(" "); } } } static void Main(string[] args) { nhap_mang(); xuat_mang(); lap: Console.WriteLine("Nhap T de tinh tong cac so nguyen to"); Console.WriteLine("Nhap G de tinh tong cac so nguyen to"); string chon = Console.ReadLine(); switch (chon) { case "T": Console.Write(tong_so_nguyen_to()); break; case "G": sap_xep_mang_so_chan(); break; default: { Console.WriteLine("Ban nhap chua dung, nhap lai"); goto lap; } } Console.ReadLine(); } } } |
Xem thêm : Tổng hợp các bài, dạng …nghành CNTT
Tổng Hợp Phần Mềm AIO Version 6.0 – Mới nhất 2017
Facebook Comments Plugin Powered byVivacity Infotech Pvt. Ltd.