当前位置:   article > 正文

C#编程题分享(5)_c#程序设计题目

c#程序设计题目

 判断质数问题

输⼊⼀个正整数,判断该数是否是质数。如果为质数输出 yes,如果不是输出no

样例输⼊113 输出yes

  1. int n = Convert.ToInt32(Console.ReadLine());
  2. int count = 0;
  3. for (int i = 1; i < n + 1; i++)
  4. {
  5. if (n % i == 0) // 判断该数能被整除
  6. {
  7. count++; // 计数器+1
  8. }
  9. }
  10. if (count == 2) // 次数为2代表1和它本身,即为质数
  11. {
  12. Console.WriteLine("yes");
  13. }
  14. else
  15. {
  16. Console.WriteLine("no");
  17. }

输出因数问题

输⼊⼀个整数,输出该整数的因数个数和所有因数。
样例输⼊ 9 样例输出 3  1  3  9

  1. int n = Convert.ToInt32(Console.ReadLine());
  2. int count = 0;
  3. string a = ""; // 定义空字符串变量,为了后面存储所有因数
  4. for (int i = 1; i < n + 1; i++)
  5. {
  6. if (n % i == 0) // 因数就是能被整除的数
  7. {
  8. count++; // 次数+1
  9. a += i + " "; // 因数存储
  10. }
  11. }
  12. Console.WriteLine(count); // 输出因数个数
  13. Console.Write(a); // 输出所有的因数

整数插入有序数组组成新的有序数组:

有n(n<=100)个整数,已经按照从⼩到⼤顺序排列好,现在另外给⼀个整数x,请将该数插⼊到序列中,并使新的序列仍然有序。输出新的序列。

样例输入:10 20 30 40 50        15   样例输出:10 15 20 30 40 50

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. string str = Console.ReadLine();// 输入有序数组
  6. // 将字符数组转换为整数数组
  7. string[] strArray = str.Split(' ');
  8. int[] intArray = new int[strArray.Length];
  9. for (int i = 0; i < strArray.Length; i++)
  10. {
  11. int num = Convert.ToInt32(strArray[i]);
  12. intArray[i] = num; // 赋值
  13. }
  14. // 给的整数x
  15. int x = Convert.ToInt32(Console.ReadLine());
  16. int nIndex = intArray.Length - 1;// 假设索引是最后一位
  17. for (int i = 0; i < intArray.Length - 1; i++)
  18. {
  19. if (x >= intArray[i] && x <= intArray[i + 1]) // 找出该整数的索引
  20. {
  21. nIndex = i;
  22. break;
  23. }
  24. }
  25. if (x < intArray[0]) // 特殊情况,该整数为最小值时
  26. {
  27. nIndex = -1;
  28. }
  29. int[] intNewArray = new int[intArray.Length + 1]; // 定义新数组
  30. // 0-nIndex = 0 - -1
  31. for (int i = 0; i < nIndex + 1; i++)
  32. {
  33. intNewArray[i] = intArray[i]; // 遍历到nIndex + 1给新数组赋值
  34. }
  35. intNewArray[nIndex + 1] = x; // 将该整数也放入新数组中
  36. // nIndex+1 -- length-1
  37. for (int i = nIndex + 1; i < intArray.Length; i++)
  38. {
  39. intNewArray[i + 1] = intArray[i]; // 从nIndex + 1开始继续遍历给新数组赋剩余的值
  40. }
  41. foreach (int num in intNewArray)
  42. {
  43. Console.Write(num + " ");// 输出新的有序数组
  44. }
  45. }
  46. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/40320
推荐阅读
相关标签
  

闽ICP备14008679号