1. 编程求s=1-2+3-4+…+99-100的和。
源程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//1.编程求s = 1 - 2 + 3 - 4 + ......+99 - 100的和。
namespace Suke.day05
{
internal class Class1
{
static void Main(string[] args)
{
int s = 0;
for (int i = 1; i <= 100; i++)
{
if (i % 2 == 1)
{
s += i;
}else if(i % 2 ==0){
s -= i;
}
}
Console.WriteLine("s = {0}", s);
Console.ReadKey();
}
}
}
运行结果
2. 试编程,利用下列公式计算π的值。
π/4=1-1/3+1/5-1/7+…+1/(4n-3)-1/(4n-1) (n=200)
源程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//2.试编程,利用下列公式计算π的值。π/ 4 = 1 - 1 / 3 + 1 / 5 - 1 / 7 + ...+1 / (4n - 3)-1 / (4n - 1)(n = 200)
namespace Suke.day05
{
internal class Class2
{
static void Main(string[] args)
{
int flag = -1;
double temp = 0;
double sum = 0;
Console.WriteLine("请输入一个整数:");
String s = Console.ReadLine();
int n = int.Parse(s);
for (int i = 1; i <= n; i++)
{
temp = 1.0 / (2 * i - 1) * flag;
sum = sum + temp;
flag = -flag;
}
sum *= -4;
Console.WriteLine(sum);
Console.ReadKey();
}
}
}
运行结果
3. 要求:打印的行数、列数由用户通过键盘输入。
****** ******
****** ******
****** ******
****** ******
源程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//3. 要求:打印的行数、列数由用户通过键盘输入。
namespace Suke.day05
{
internal class Class3
{
static void Main(string[] args)
{
Console.Write("请输入行数:");
String row = Console.ReadLine();
int r = int.Parse(row);
Console.Write("请输入列数:");
String col = Console.ReadLine();
int c = int.Parse(col);
for (int i = 1; i <= r; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write(" ");
}
for (int k = 1; k <= c; k++)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.WriteLine();
for (int i = 1; i <= r; i++)
{
for (int j = 0; j < r - i; j++)
{
Console.Write(" ");
}
for (int k = 1; k <= c; k++)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.WriteLine();
for (int i = 1; i <= r; i++)
{
for (int j = 1; j < 7 - i; j++)
{
Console.Write(" ");
}
for (int k = 1; k < c; k++)
{
Console.Write("*");
}
for (int n = 1; n < 2 * i - 1; n++)
{
Console.Write(" ");
}
for (int m = 1; m < c; m++)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
运行结果
4. 编写控制台应用程序,用两个一维数组存放5个学生的学号和姓名进 行排序,并输出排序后的结果。
源程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//4.编写控制台应用程序,用两个一维数组存放5个学生的学号和姓名进行排序,并输出排序后的结果。
namespace Suke.day05
{
internal class Class4
{
static void Main(string[] args)
{
int[] id = {124,148,132,123,151};
String[] name = { "东邪黄药师", "西毒欧阳锋", "南帝段智兴", "北丐洪七公", "中神通王重阳" };
Console.WriteLine("学号、姓名排序前:");
for(int i = 0; i < 5; i++)
{
Console.WriteLine("学号:{0},姓名:{1}",id[i],name[i]);
}
Console.WriteLine();
Console.WriteLine("学号、姓名排序后:");
Array.Sort(id, name);
for (int i = 0; i < 5; i++)
{
Console.WriteLine("学号:{0},姓名:{1}", id[i], name[i]);
}
Console.ReadKey();
}
}
}