前言
利用模仿井字棋代码,编写一个应用简易计算器
一、实际演示
演示过程如视频所示:
lab03--简易计算器演示
二、代码
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Calculator : MonoBehaviour
{
public string str_res;
public static string str_a;
public static string str_b;
public static string str_opera;
float res;
void Start()
{
Init();
}
void Init()
{
str_res = "0";
str_a = "";
str_b = "";
str_opera = "";
res = 0;
}
void OnGUI()
{
GUI.Box(new Rect(0, 0, 350, 220), "");
//对数字进行处理
if (GUI.Button(new Rect(0, 0, 50, 30), "1"))
{
str_a += "1";
str_res = str_a;
}
if (GUI.Button(new Rect(60, 0, 50, 30), "2"))
{
str_a += "2";
str_res = str_a;
}
if (GUI.Button(new Rect(120, 0, 50, 30), "3"))
{
str_a += "3";
str_res = str_a;
}
if (GUI.Button(new Rect(180, 0, 50, 30), "4"))
{
str_a += "4";
str_res = str_a;
}
if (GUI.Button(new Rect(0, 40, 50, 30), "5"))
{
str_a += "5";
str_res = str_a;
}
if (GUI.Button(new Rect(60, 40, 50, 30), "6"))
{
str_a += "6";
str_res = str_a;
}
if (GUI.Button(new Rect(120, 40, 50, 30), "7"))
{
str_a += "7";
str_res = str_a;
}
if (GUI.Button(new Rect(180, 40, 50, 30), "8"))
{
str_a += "8";
str_res = str_a;
}
if (GUI.Button(new Rect(0, 80, 50, 30), "9"))
{
str_a += "9";
str_res = str_a;
}
if (GUI.Button(new Rect(60, 80, 50, 30), "0"))
{
str_a += "0";
str_res = str_a;
}
//计算符号
if (GUI.Button(new Rect(120, 80, 50, 30), "+"))
{
str_opera = "+";
print(str_b);
if (str_a != null)
{
str_b = str_a;
}
str_a = "";
str_res = str_b;
}
if (GUI.Button(new Rect(60, 120, 50, 30), "-"))
{
str_opera = "-";
if (str_a != null)
{
str_b = str_a;
}
str_a = "";
str_res = str_b;
}
if (GUI.Button(new Rect(0, 120, 50, 30), "*"))
{
str_opera = "*";
if (str_a != null)
{
str_b = str_a;
}
str_a = "";
str_res = str_b;
}
if (GUI.Button(new Rect(180, 80, 50, 30), "/"))
{
str_opera = "/";
if (str_a != null)
{
str_b = str_a;
}
str_a = "";
str_res = str_b;
}
if (GUI.Button(new Rect(0, 160, 50, 30), "C"))
{
if (str_a == "")
{
str_res = "0";
return;
}
else
{
str_a = str_a.Substring(0, str_a.Length - 1);
}
str_res = str_a;
}
if (GUI.Button(new Rect(120, 120, 50, 30), "="))
{
if (str_opera == "+")
{
res = float.Parse(str_b) + float.Parse(str_a);
}
else if (str_opera == "-")
{
res = float.Parse(str_b) - float.Parse(str_a);
}
else if (str_opera == "*")
{
res = float.Parse(str_b) * float.Parse(str_a);
}
else if (str_opera == "/")
{
res = float.Parse(str_b) / float.Parse(str_a);
}
str_b = res.ToString();
str_a = "";
str_res = res.ToString();
}
if (GUI.Button(new Rect(180, 120, 50, 30), "CE"))
{
str_a = "";
str_a = "";
res = 0;
str_res = "";
}
GUI.Label(new Rect(300, 0, 100, 30), str_res);
}
}