用C#控制台程序写一个。客户输入一个数字,打印其平方,但是如果输入有误,程序不断提示客户重新输入。,

直到正确为止。(用上try catch)

using System;

using System.Windows.Forms;

namespace pow

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        /// <summary>

        /// 计算按扭点击事件

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnCalc_Click(object sender, EventArgs e)

        {

            

           //这第一个方法,使用try catch

            try

            {

                int a = Convert.ToInt32(txtValue.Text);//将输入的内容转换为整型

                txtDisplay.Text=Math.Pow(a,2).ToString();//在上面的文本框中显示输入值的2次方

            }

            catch (Exception ex)

            {

                //如果转换不成功,就什么报错,要求重新输入

                MessageBox.Show("请输入一个数字,"+ex.Message+"请重新输入!");

            }

            //这是第二种方法

           // if (!int.TryParse(txtValue.Text, out a))

            //{

              //  MessageBox.Show("请输入一个数字!");

                //return;

            //}

            //txtDisplay.Text = Math.Pow(a, 2).ToString();*/

        }

    }

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-23
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 平方
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("请输入一个正确的数字:");
string str_input = Console.ReadLine();
try
{
int value = Convert.ToInt32(str_input);
Console.WriteLine(string.Format("平方是:{0}", value * value));
Console.ReadLine();

break;
}
catch (Exception e)
{
Console.WriteLine("您的输入错误," + e.Message);
}
}
}
}
}本回答被提问者采纳
第2个回答  2011-05-23
int main(){
while(true){
Console.WriteLine("请输入数字:");
sring input = Console.ReadLine();
try{
int value = Convert.ToInt32(input);
Console.WriteLine(string.Format("它的平方是:{0}", value * value));
}catch(Execption ex){
Console.WriteLine("你输入的东西有问题,请重新输入!错误原因:" + ex.Message);
}
}
}追问

你的这个程序就算输入的是正确的可还是会要求继续输入。
我的意思是说正确的话就跳出循环

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网