美文网首页
读取txt文件中计算式并计算输出

读取txt文件中计算式并计算输出

作者: 织田信长 | 来源:发表于2015-07-17 11:47 被阅读117次

       刚学习ruby,做了个读取txt中计算式,计算出后果再写入txt文件。但是因为目前能力有限,只完成了有“+”,“—”,"*“,”/“,并且只有一个运算负的算式。本打算将计算完的结果写入原txt文中“=”的后面,但是没有找到好的方法解决,便将结果写入到了一个新的txt文件中。在读取过程中,除了第一行的算式包含三个字符以外,后面的算式都包含四个字符,一开始没有注意到回车符的问题,总是不能计算除第一个算式以外的算式。以后要慢慢完善功能。


str=File.open("number.txt").read

array = str.split('=')

txt = File.open("numberend.txt","w+")

i =0

while i <=  array.size

nums =array[i]

puts nums

if i == 0

if nums[1] =="+"

txt.puts nums[0].to_i+nums[2].to_i

elsif nums[1] =="-"

txt.puts nums[0].to_i-nums[2].to_i

elsif nums[1] =="*"

txt.puts nums[0].to_i*nums[2].to_i

else nums[1] =="/"

if nums[2]=="0"

txt.puts "The divisor is not zero !"

else

txt.puts nums[0].to_i/nums[2].to_i

end

end

else

if nums[2] =="+"

txt.puts nums[1].to_i+nums[3].to_i

elsif nums[2] =="-5"

txt.puts nums[1].to_i-nums[3].to_i

elsif nums[2] =="*"

txt.puts nums[1].to_i*nums[3].to_i

else nums[2] =="/"

if nums[3] =="0"

txt.puts "The divisor is not zero !"

else

txt.puts nums[1].to_i/nums[3].to_i

end

end

end

i+=1

end

相关文章

  • 读取txt文件中计算式并计算输出

    刚学习ruby,做了个读取txt中计算式,计算出后果再写入txt文件。但是因为目前能力有限,只完成了有“+”...

  • sed命令学习

    sed命令详解 假设文件t1.txt内容为 常用组合 替换并输出: 读取test.txt并输出控制台,其中替换所有...

  • 长知识系列 - 收藏集 - 掘金

    SpringBatch 读取 txt 文件并写入数据库 - 后端 - 掘金SpringBatch 读取 txt 文...

  • 长知识 - 收藏集 - 掘金

    SpringBatch 读取 txt 文件并写入数据库 - 后端 - 掘金SpringBatch 读取 txt 文...

  • Winform文件相关操作

    复制文件 获取文件夹下的所有文件名称 创建txt文件,并写入数据 读取txt文件 选择文件夹

  • 运维基础知识-日志分析

    1.从文件中读取关键词进行搜索 且显示行号输出test.txt文件中含有从test2.txt文件中读取出的关键词的...

  • Python 文件

    新建文件 pi_digits.txt 及内容: 读取整个文件 逐行读取 将文件各行内容读入列表 实例输出结果: 圆...

  • TLCL学习笔记之四 重定向

    标准输入,输出,和错误 cat命令:读取一个或多个文件,然后复制到标准输出。 “cat test.txt”读取文本...

  • 读取txt文件

    """ 读取txt文件txt文件使我们经常操作的文件类型,Python提供了以下几种读取txt文件的方法。read...

  • PHP文件读写方法

    1.readfile() 读取文件,并把它写入输出缓冲。 readfile("demo.txt"); 2.fop...

网友评论

      本文标题:读取txt文件中计算式并计算输出

      本文链接:https://www.haomeiwen.com/subject/fthpqttx.html