练习 - 生成计算器程序
在本练习中,你将继续处理在第一个练习中创建的计算器程序。 利用所有这些来之不易的知识,实现其余功能,如用户输入,并应用算术运算符。
从控制台读取
在本部分中,你将支持从控制台读取。
转到目录 Variables,然后打开 文件。
找到下列代码:
printfn "Welcome to the calculator program" // read input from the console and assign to `sum` let sum = 0 printfn "The sum is %i" sum使用以下代码替换已注释的行:
printfn "Type the first number" let firstNo = System.Console.ReadLine() printfn "Type the second number" let secondNo = System.Console.ReadLine() printfn "First %s, Second %s" firstNo secondNo保存文件,然后运行程序。
运行命令
dotnet run。dotnet run当系统要求输入时,填写 1 和 2。
输出如下所示:
Welcome to the calculator program Type the first number 1 Type the second number 2 First 1, Second 2 The sum is 0现在,你就可以支持用户输入了,但需要实际计算程序,我们来继续操作。
执行计算
要添加程序的计算部分,将用户输入转换为数字并应用算术运算符。
找到如下所示的行:
let sum = 0将其更改为以下代码:
let sum = (int firstNo) + (int secondNo)保存更改并重新运行程序。
运行命令
dotnet run。dotnet run当系统要求输入时,输入 1 和 2。
你将看到类似如下的输出:
Welcome to the calculator program Type the first number 1 Type the second number 2 First 1, Second 2 The sum is 3
祝贺你! 你的计算器程序按预期方式工作。