C#本质论学习第二天

Posted on 2012-11-12 22:50  赵明威  阅读(299)  评论(0)    收藏  举报

 希望大家多来评论和指导

一、控制台输入和输出

1.从控制台输出

System.Console.WriteLine()用来输出文本,并切换到下一行,用法System.Console.WriteLine(“HelloWorld”)或者带变量的System.Console.WriteLine(“{0}{1}”,a,b),其中{0}{1}代表了a,b的前后位置,如果写的是{1}{0}输出的a,b的顺序就会改变的,

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace String
 7 {
 8     class Program
 9     {
10         static void Main()
11         {
12             string text1,text2, firstname="zhao", lastname="mingwei";
13             text1 = string.Format("your full name is {0}{1}.", firstname, lastname);
14             text2 = string.Format("your full name is {1}{0}.", firstname, lastname);
15             System.Console.WriteLine(text1);
16             System.Console.WriteLine(text2);
17             System.Console.ReadKey();
18         }
19     }
20 }

输出:

System.Console.Write(),输出文本,除了不能直接切换到下一行之外,其他与System.Console.WriteLine()相同。把上程序的改为Write后输出为

2.从控制台读取输入

System.Console.ReadLine()用于读取输入的文本,并且切换到下一行,读取的文本的数据类型为“string”类型,不能隐式的转化为整型,所以要注意,在把读取的值赋值给一个变量的时候,那个变量的类型也应该是string的。或者用int.Parse()进行类型的转换。

int a;         
a=System.Console.ReadLine();
1 int a;            
2 a=int.Parse(Console.ReadLine());
3 Console.WriteLine("{0}",a);             
4  Console.ReadKey();

 System.Console.Read()读取与字符对应的一个整数,如果没有更多的字符可用,就返回-1;为了获取实际的字符,需要用整型变量接收数据,再将整数转化为一个字符,

另外除非按回车键,否则System.Console.Read()不会返回输入,即是在回车之前,不会对字符进行处理。

1 int real;
2 char ch;
3 real=System.Console.Read();
4 ch=(char)real;
5 System.Console.Write(ch);

最后在程序的运行过程的时候,为了防止执行窗口一闪而过,就要再加一句System.Console.ReadKey()。编了一个五十个数内的斐波拉契数列,如有异议,请指教,

输出如下图

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Fibonaci
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             int an1 = 1;
13             int an2 = 1;
14             
15             Console.Write("{0}\t",an1);
16 
17             while (an2 < 50)
18             {
19                 Console.Write("{0}\t",an2);
20                
21                 an2 = an2 + an1; 
22                 an1 = an2-an1;
23             }
24             Console.ReadKey();
25         }
26     }
27 }

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3