I've got decompiled source codes, they got simple errors like below:
this.SubReport.Top = 77.0 / 16.0;
Error 18 Cannot implicitly convert type 'double' to 'float'. An
explicit conversion exists (are you missing a
cast?)
The solution is simple:
this.SubReport.Top = (float)(77.0 / 16.0);
// or
this.SubReport.Top = 77.0f / 16.0f;
However there are tons of lines. What is the easiest way to clear these errors except replacing text? Because that's why I'm asking the question, I don't want to use keyboard & replace every single error, there are 1000+ lines. Doubleclicking the error & surrounding the numbers with (float) is my last resort.
You can use Find & Replace with RegEx options
Example:
Input: this.SubReport.Top = 77.0 / 16.0;
Output: this.SubReport.Top = (float)(77.0 / 16.0);
Edit:
Also you could use groups to add the float f to the values other than casting
Input: this.SubReport.Top = 77.0 / 16.0;
Output: this.SubReport.Top = 77.0f / 16.0f;
Try to help yourself and automate Find and Replace with regular expressions. For example, you can change all divides:
Then find other such patterns to replace them automatically.
Another approach is to change Top to a property with a double type. Then, inside the property you can do the casting.
float _top = 0.0;
double Top
{
set
{
_top = (float)value;
}
get
{
return _top;
}
}
You could also use something like Resharper to refactor code paths that access the getter for Top and introduce another property in its place as a floating point type that returns (float)Top in its property. Something like:
float FloatTop
{
get
{
return (float)Top;
}
}
Related
I have a CSV with the following data (no header)
12,2010,76.5
2,2000,45
12,1940,30.2
and I'm reading the data into a List<List<object>>.
To know what's in each line and column / row I'm using the following loop
List<List<object>> data = CSVReaderNoHeader.Read("input")
for (var i = 0; i < data.Count; i++)
{
double month = (double)(int)data[i][0];
print($"month:{month} ////END");
double year= (double)(int)data[i][1];
print($"year:{year} ////END");
double temperature= (double)data[i][2];
print($"temperature:{temperature} ////END");
}
Yes I need to create doubles, that's why I'm unboxing and casting (could have use double.Parse instead).
I'm able to print the month and the year just fine, but when reaching double temperature= (double)data[i][2];, throws the following error
InvalidCastException: Specified cast is not valid.
I printed what's in data[i][2] before that line (print(data[i][2]);) just to see if everything was in order there and got 76.5 as expected. Then, tested also using
double temperature= (double)(double)data[i][2];
double temperature= (double)(float)data[i][2];
(which i think it would be unnecessary to add that extra (double) / (float)) and
object tempr = data[i][2];
double temperature;
temperature = (double)tempr;
but the problem remained. So, I went on and ran print(data[i][2].GetType()); to see if the type returned there could be cast into a double. I got as result System.String.
Knowing this, then I tried then the methods double.TryParse, double.Parse and Convert.ToDouble but none worked
double.TryParse(data[i][2], out temperature);
Argument 1: cannot convert from 'object' to string.
double temperature = double.TryParse(data[i][2]);
Argument 1: cannot convert from 'object' to string.
double temperature = System.Convert.ToDouble(data[i][2]);
FormatException: Input string was not in a correct format.
How then I have to cast it?
Because your numbers use a point as decimal separator and your system localization can use a different, you can use that:
using System.Xml;
double temperature = XmlConvert.ToDouble(data[i][2].ToString());
It will raise an exception in case of parsing error.
So you can try...catch to manage it.
Perhaps you will need to add System.Xml to assembly references of the project.
Else you can use #Fabjan solution:
if (double.TryParse(data[i][2].ToString(),
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture,
out var temperature);
IsOk();
else
IsNotOk();
So I'm supposed to build a form with a class that calculates the miles driven and miles used to find out what the miles per gallon is.
In my form, my code:
//Create a default value of 0.
double dblDefault = 0;
//Create a TryParse if the input is double, if not, show error message.
if (!double.TryParse(txtDriven.Text, out dblDefault))
{
dblDefault = -1;
}
//Separation line...
if (dblDefault >= -1)
{
double dblDriven = double.Parse(txtDriven.Text);
double dblUsed = double.Parse(txtUsed.Text);
CMilesPerGallon CTrans = new CMilesPerGallon();
double dblMpgTotal = CMilesPerGallon.numofmiles(dblDriven);
lblMpgTotal.Text = dblMpgTotal.ToString("C");
}
//If user inputs negative values, display message box for error.
else
{
MessageBox.Show("Invalid input, must be a positive 'double' value.");
}
In my class, my code:
public class CMilesPerGallon
{
//Create calculation method.
public double calculate(double numofmiles, double numofgallons)
{
//Acquire the math.
double mpg = numofmiles / numofgallons;
//Return the MPG.
return mpg;
}
}
I know somewhere in there I did something wrong, but I can't seem to figure it out. The only error so far I got is, 'double dblMpgTotal = CMilesPerGallon.numofmiles(dblDriven)'. Because 'numofmiles'does not contain a definition.
There's no method called numofmiles within your CMilesPerGallon class, However, I'd assume you wanted to pass dblDriven and dblUsed as the arguments to the calculate method.
e.g
double dblMpgTotal = CTrans.calculate(dblDriven, dblUsed);
note that the calculate method operates on the CTrans instance rather than being called directly via the class CMilesPerGallon as it's not static.
There are two problems with the code
- Calling the method with class name
- Calling a variable name as the method name and that variable also is not available in that scope.
I have kept your code to explain the problem and edited it to show how it should be called.
In the code part
CMilesPerGallon CTrans = new CMilesPerGallon();
double dblMpgTotal = CMilesPerGallon.numofmiles(dblDriven);
lblMpgTotal.Text = dblMpgTotal.ToString("C");
on the line
double dblMpgTotal = CMilesPerGallon.numofmiles(dblDriven);
You are calling the method numofmiles using the class name whereas you should use the object name you created as
double dblMpgTotal = CTrans.numofmiles(dblDriven);
Only static methods can be called with ClassName.MethodName. Using cTrans should fix your problem. And if you don't have a method numofmiles and you want to use calculate method then you just need to call as
double dblMpgTotal = CTrans.calculate(dblDriven, dblUsed);
Hope it helps.
I understand, I am not providing the answer you were looking for, but trust me, I am providing the answer that you need. There are few basic concepts of programming that you need before you can go around and complete a full program. Seeing your question, I cannot give you a direct answer because truly there is none. But I will point you to the right direction, the rest depends on you.
Please try to collect the answers of the following questions, I am pretty sure, when you collect all the answers of the following questions, you will understand what was the problem -
Difference between defining a Function/Method and executing Function/Method
Passing Values as Parameters to functions
What is Object Oriented Programming
Difference between a class and object, similarly difference between class methods and object methods
There are more, but lets start with these.
You have a misunderstanding of your variable scope. The variables numofmiles and numofgallons don't exist in your calling context, which uses dblDriven and dblUsed. So it should be:
double dblDriven = double.Parse(txtDriven.Text);
double dblUsed = double.Parse(txtUsed.Text);
CMilesPerGallon CTrans = new CMilesPerGallon();
double dblMpgTotal = CTrans.calculate(dblDriven, dblUsed);
I need to read from file mathematical expression and evaluate it's value. Example expression formats are as follow:
"5" - constant
"3.1415 * 0.25" - constant expressions
"{0} - 50" - expressions with value placeholders (String.Format())
"Abs({0} - 50)" - just like up but with mathematical functions
I was using so far NCalc which worked great until it had to deal with expressions like follow:
"3.0 * Abs({0} + 34)"
Unfortunately in example just above the result of following code:
var value = ReadValueFromSomewhere(); // Lets say it returns 125.75
var exprStr = ReadExpression(); // returns: "3.0 * Abs({0} + 34)"
var toEval = String.Format(exprStr, value);
var result = new NCCalc.Expression(toEval).Evaluate()
is following exception:
System.InvalidOperationException
Operator '*' can't be applied to operands of types 'double' and 'decimal'
NCalc.Numbers.Multiply(object, object)
NCalc.Domain.EvaluationVisitor.Visit(NCalc.Domain.BinaryExpression)
NCalc.Domain.BinaryExpression.Accept(NCalc.Domain.LogicalExpressionVisitor)
NCalc.Expression.Evaluate()
It seems like Abs() method returns decimal and NCalc can't handle doing calculations between double and decimal (propably bug?). So I would like to ask what alternative libraries I could use instead of NCalc? Or perhaps there is other workaround than expression:
"Abs(3.0) * Abs({0} + 34)"
?
What do you mean by "expressions with value placeholders"? Can you give more specific example? You can try mXparser - it works for Java and .NET.
Example of usage:
Expression e = new Expression("3.1415 * 0.25");
double v = e.calculate();
Follow mXparser tutorial.
Regards
How do I make If statements using floats? The code I have is as follows:
{float p1 = float.Parse(textBox1.Text);
if (p1 == ""){MessageBox.Show("Home");}}
The p1 if statement on the second line does not work. How do I make a proper if statement for this?
EDIT: I should explain. The goal is to check for an empty box. I can't use a string command since I want this to interpret numbers.
Thanks in advance for the help.
float values cannot be "empty". If you try parsing an empty string into a float, you would get a runtime error.
You need to check the string for being empty before parsing, and then parse with a more "conservative" TryParse method that does not throw an exception.
if (string.IsNullOrWhitespace(textBox1.Text)) {
MessageBox.Show("Home");
}
float p1;
if (!float.TryParse(textBox1.Text, out p1)) {
MessageBox.Show("textBox1 is not a float");
}
Note: In general, comparing floats for equality with == operator is not a good idea, because float is not an exact representation. This Q&A discusses the problem in Java, but the issue is relevant in all languages that use floating point representation.
If you are attempting to check whether or not it was able to successfully parse a float value from textBox1.Text, use TryParse instead like so:
float p1;
if (float.TryParse(textBox1.Text, out p1))
{
MessageBox.Show("Home");
}
If you're simply trying to check for an empty text box, you could do this instead:
if (!String.IsNullOrEmpty(textBox1.Text))
{
// Now we can try to parse p1 (assuming it's a valid number)
float p1 = float.Parse(textBox1.Text);
MessageBox.Show("Home");
}
Note that you would also have to handle invalid characters this way (such as letters, symbols, or spaces).
private void buttonConvert_Click(object sender, EventArgs e)
{
//Convert number from C to F
double convertDecimal;
convertDecimal = 1.8;
textBoxF = double.Parse(textBoxC.Text) * double(convertDecimal) + 32;
^here is where I get the error
Error 1 Invalid expression term 'double'
I am pretty new to programming and but I just can't wrap my mind around trying to add, subtract, dividing, or multiplying numbers. I am trying to do a simple a simple conversion. Take the number from the Celsius textbox and convert it to Fahrenheit. I just don't understand the number part???
Thanks for your help!
double(convertDecimal) should be (double)convertDecimal
That looks like a C++ type-casting expression, which doesn't work in C#. And as convertDecimal already is of type double there's no need to cast it. Just use it directly:
textBoxF = double.Parse(textBoxC.Text) * convertDecimal + 32;
You only need to change the type of a variable (i.e. type-cast) when the variable is of a type not expected. Adding two double values is okay. Even adding a double and an int is okay because the integer is implicitly converted to a double.
Edit: You try to assign the result of the expression to a control, which will not work. You should convert the result to a string (e.g. with double.ToString), and then assign to the controls text field:
double farenheit = double.Parse(textBoxC.Text) * convertDecimal + 32;
textBoxF.Text = farenheit.ToString();