请出一道大二学生水平的C#习题
时间: 2023-08-10 18:10:40 浏览: 45
好的,请编写一个程序,输入一个整数n,然后输出从1到n之间所有偶数的平方。如果n不是正整数,输出错误信息。以下是代码示例:
```csharp
using System;
class MainClass {
public static void Main (string[] args) {
Console.Write("请输入一个正整数n:");
int n = int.Parse(Console.ReadLine());
if(n <= 0) {
Console.WriteLine("输入错误,请输入正整数!");
} else {
Console.WriteLine($"1到{n}之间所有偶数的平方为:");
for(int i = 2; i <= n; i += 2) {
Console.Write($"{i * i} ");
}
}
}
}
```
这个程序首先会提示用户输入一个正整数n,然后使用 `int.Parse()` 方法将用户输入的字符串转换为整数类型。如果n小于等于0,则输出错误信息;否则,使用for循环遍历从2到n之间的所有偶数,并输出它们的平方。注意,这里使用了字符串插值(string interpolation)的语法,即在字符串中插入变量的值,使得代码更加简洁易懂。
相关问题
请出一道C#基础练习题
好的,以下是一道C#基础练习题:
定义一个名为Person的类,该类具有以下属性和方法:
属性:
- name:表示人的姓名,类型为string。
- age:表示人的年龄,类型为int。
方法:
- introduce:用Console.WriteLine()输出这个人的姓名和年龄。
要求:
- 定义Person类。
- 在Main函数中创建一个Person对象,并为其属性赋值。
- 调用Person对象的introduce方法输出该人的姓名和年龄。
示例代码如下:
```csharp
using System;
class Person
{
public string name;
public int age;
public void introduce()
{
Console.WriteLine("My name is {0}, and I am {1} years old.", name, age);
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.name = "Tom";
p.age = 20;
p.introduce();
}
}
```
运行结果:
```
My name is Tom, and I am 20 years old.
```
C#练习题VS2019
以下是一个C#练习题的例子,你可以在VS2019中尝试编写和运行它:
```csharp
using System;
namespace Exercise
{
class Program
{
static void Main(string[] args)
{
// 填空题
int num1 = 10;
int num2 = 20;
int sum = num1 + num2;
Console.WriteLine("The sum is: " + sum);
// 选择题
int x = 5;
int y = 10;
int z = 15;
int result = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
Console.WriteLine("The largest number is: " + result);
// 判断题
int a = 5;
int b = 10;
bool isGreater = (a > b);
Console.WriteLine("Is a greater than b? " + isGreater);
// 编程题
int[] numbers = { 1, 2, 3, 4, 5 };
int sumOfNumbers = 0;
foreach (int number in numbers)
{
sumOfNumbers += number;
}
Console.WriteLine("The sum of numbers is: " + sumOfNumbers);
}
}
}
```
这个例子包含了填空题、选择题、判断题和编程题。你可以在VS2019中创建一个新的C#控制台应用程序项目,将上述代码复制到`Program.cs`文件中,并运行该程序来查看结果。