简体   繁体   English

我如何只读取包含数字的文本文件的第一行,并进行数学运算?

[英]how do i read the first line only of a text file which contains numbers and do maths with it?

I have a text file which contains a list of numbers. 我有一个包含数字列表的文本文件。 the first line is 5.5, the second line is 8 third line is 13 and so on. 第一行是5.5,第二行是8,第三行是13,依此类推。 Each text file generates a list of number different each time but I'm only concentrating on the first line which in this case is 5.5, here is my code 每个文本文件每次都会生成一个不同的数字列表,但是我只专注于第一行,在这种情况下为5.5,这是我的代码

                StreamReader FileFav = new StreamReader(BettingFileFav);
                StreamReader FileOdds = new StreamReader(BettingFileOdds);
                StreamReader FileResult = new StreamReader(BettingFileResult);
                FavLine = FileFav.ReadLine();
                OddsLine = FileOdds.ReadLine();
                ResultLine = FileResult.ReadLine();
                int BetAmount = 10;

                if (FavLine.Contains("Yes"))
                {
                    int a = Convert.ToInt16(OddsLine);
                    double c = ((double)a * BetAmount);
                    string myString = c.ToString("#.##");
                    MessageBox.Show("Won £" + myString);
                }
                else
                {
                    MessageBox.Show("Lost -£" + BetAmount); 
                }

the line of text it has read reads 5.5 so I am trying to get the answer 55.50. 它已阅读的文本行显示为5.5,所以我尝试获得答案55.50。 I get an error code 我收到错误代码

Additional information: Input string was not in a correct format. 附加信息:输入字符串的格式不正确。

I'm using the MessageBox.Show to see if it works then migrating the result to a file which I will be using later. 我正在使用MessageBox.Show看看它是否有效,然后将结果迁移到一个文件中,稍后我将使用它。

Can anybody help? 有人可以帮忙吗?

As was pointed out in the comments, you are trying to convert a floating point number to an integer, which is not accepted by Convert.ToInt16 . 如注释中所指出,您正在尝试将浮点数转换为整数,而Convert.ToInt16不接受该整数。 The function requires the string to represent an actual signed integer value that fits within 16 bits, as described in the documentation . 该函数需要字符串来表示一个实际的有符号整数值,该整数值适合16位,如文档中所述。

However based on your following calculation, what you really want to do is convert the string to a double straight away, so you should use Convert.ToDouble instead. 但是,根据您的以下计算,您真正想要做的是立即将字符串转换为double Convert.ToDouble ,因此应改用Convert.ToDouble

So the lines 所以线

int a = Convert.ToInt16(OddsLine);
double c = ((double)a * BetAmount);

should become 应该成为

double a = Convert.ToDouble(OddsLine);
double c = (a * BetAmount);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM