strange issue with double.parse conversion [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Im using visual studio 2010, windows form.
I have this code, that permit to convert money from USD to EUR. This is reference: http://www.codeproject.com/Articles/17909/Simple-Class-to-get-Currency-Exchange-Rates
This is code:
CurrencyConverter2 cc = new CurrencyConverter2();
cc.AdjustToLocalTime = true;
CurrencyData cd = new CurrencyData("USD", "EUR");
// Convert US Dollars to Euros
cc.GetCurrencyData(ref cd);
label5.Text = (5000 / cd.Rate).ToString();
OUTPUT IN THIS CASE IS : 3753,75375375375
But if I place value (example 5000) from texbox in this way:
double cambiamo = double.Parse(tbxDaConvertire.Text);
tbxConvertito.Text = (cambiamo * cd.Rate).ToString();
OUTPUT IS: 3752,5
I dont understand because Im getting this value!
How can I solve it please?

As comments have pointed out:
double cdRate = 1.42f;
var value1 = (5000 / cdRate).ToString();
var value2 = (double.Parse("5000") / cdRate).ToString();
var value3 = (5000.0f / cdRate).ToString();
// value1 = "3521.12686697913"
// value2 = "3521.12686697913"
// value3 = "3521.12686697913"
It is most likely that your CD rate is different. For a start in your first example you use 5000 / cd.Rate and in your second you use 5000 * cd.Rate - have you at some time performed cd.Rate = 1/cd.Rate? That could be where the discrepancy is arising.

Your first conversion used a conversion rate of 0.75075
Your second conversion used a conversion rate of 0.75050
Just a 0.00025 difference, easily found back in this chart of the conversion rate of the past week:
Note the extreme volatility, the rate changes in minutes. Or to put it another way, it changed while you edited your code. Clearly you are getting live updates from your currency conversion service.

Related

Solving project euler number 6 in C# [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to solve the Project Euler problem number 6 with the following program:
double counter = 1;
double sumsquare = 0;
double squaresum = 0;
while (counter <= 100)
{
sumsquare += Math.Pow(counter, 2);
squaresum += counter;
counter++;
}
Math.Pow(squaresum, 2);
Console.WriteLine("the sum is {0} ,the square is :{1}", squaresum.ToString(), sumsquare.ToString());
double diff = sumsquare - squaresum;
Console.WriteLine(diff.ToString());
Console.ReadLine();
However, the answer was wrong. Can anyone tell me what the problem is with my code?
You have an error in that you are computing a power and then discarding it.
More generally, you should avoid double when solving PE problems that involve integers. Doubles are only accurate to fifteen decimal places; after that, they round off.
Better types to use are long, which can represent integers up to 9,223,372,036,854,775,807 or decimal, which can represent integers up to 79,228,162,514,264,337,593,543,950,335, or BigInteger, which can represent arbitrarily large values.
Note that code typically gets slower as you use the larger and larger types.
Even more generally, now would be a good time to learn how to use a debugger. Figure out what the output of your program should be for a very small case that you can calculate by hand. Then step through your program line by line and see where it goes wrong. That is a far more efficient way to debug a problem than asking the internet.
You seem to think that Math.Pow(squaresum, 2); modifies squaresum. That's not so: it returns a square of squaresum, and you should assign it to squaresum if you want the variable to be modified.
squaresum = Math.Pow(squaresum, 2);
Also the idea of using double type here is not quite good, but it appears that you won't lose enough precision here to get a wrong result.

What should I use in this case? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need to go through two arraylists (for the ones answering my previous question, I've solved it), one ("dir") has text saved on it which will be used as an Instruction, and the other one ("time") has numbers in it wich will be used for the Interval of a Timer ("Timer.Interval"). What I need to do is to make each position of "Dir" be done continiously until the timer ticks (Timer.Tick), then go to the next position.
This is as far as I got:
int i = 0;
for ( i = 0; i > -1; i++)
{
Console.WriteLine(cls.dir[i]);
Console.WriteLine(cls.time[i]);
if (cls.dir[i] == "one")
{
timerSeconds.Interval = Convert.ToInt32(cls.time[i]) * 1000;
Label1.Text = "Hello StackOverflow";
}
}
In this case to make it more easy to understand I made and example, what it's supposed to do is to show a different text as a sign in the Label1 as long as the time Arraylist says for each block. I know this is incomplete, how would you end it?
It sounds like you want to "wait" a certain number of milliseconds.
If so, the best way to do this is with a "Sleep":
if (cls.dir[i] == "one")
{
int interval = Convert.ToInt32(cls.time[i]) * 1000;
Label1.Text = "Hello StackOverflow";
System.Threading.Thread.Sleep(interval);
}
Label1.Text = "Time to wake up";

Changing date-time format in c# [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Creating digital clock. I'm newbie to C#. My code look like that
timeLbl.Text = DateTime.Now.ToLongTimeString();
dateLbl.Text = DateTime.Now.ToLongDateString();
Here is, the result
http://content.screencast.com/users/TT13/folders/Jing/media/da6d1f65-bf5f-4735-97dc-70485112a998/2012-07-02_1826.png
I got some questions:
Can I change time's format to 24 Hour? how?
How to change date into digits only format (like dd/mm/yyyy) or this result but in exact language (I mean, words "Monday, July" in another language, which windows support, for ex Turkish)?
How to make window dynamically change it's width (depending on text
length)?
Please help me,to achieve these 3 things. Thx in advance
Ans 1:
timeLbl.Text = DateTime.Now.ToString("HH:mm:ss");
Will convert time to 24 hour format.
Ans 2:
dateLbl.Text = DateTime.Now.ToString("dd/MM/yyyy");
Will convert date format to 31/06/2012
More formats here
The first and second point where been answered, for the last point set SizeToContent="WidthAndHeight" on the window and the window will dynamically resize based on its content size. I assume ur working with wpf, else it doesnt works!

Array assignment to string [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have php code that puts some values into an Array as follows:
$hunter=addslashes($MessageArray[1]);
$time=addslashes($MessageArray[2]);
I wrote the same code in C# and wanted to know if it was correct.
string Hunter = Messagearray[1].tostring();
string time = Messagearray[2].tostring();
As James mentioned, use Pascal casing:
string hunter = messageArray[1].ToString();
string time = messageArray[2].ToString();
Also, C# arrays are indexed starting at 0. You can change the starting index of arrays in PHP, but you can't in C#. Perhaps you do wish to take the 2nd and 3rd items, but keep it in mind. You might want:
string hunter = messageArray[0].ToString();
string time = messageArray[1].ToString();
As far as addslashes() goes, it will depend on your usage of hunter and time. If you're using them in a SQL statement, there are other ways of accomplishing the functionality of PHP's addslashes().
Snipped from Here
public static string AddSlashes(string input)
{
return System.Text.RegularExpressions.Regex.Replace(input, #"(\\)([\000\010\011\012\015\032\042\047\134\140])", "$2");
}
Usage:
//
var Messagearray = new object[] { "item 0", 1 };
var hunter = AddSlashes(Messagearray[0].ToString());
var time = AddSlashes(Messagearray[1].ToString());

C# code or algorithm to quickly calculate distance between large strings? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Hi and thanks for looking!
Background
I have an XML file that contains 1900 nodes which themselves contain a string of encoded data of about 3400 characters.
As part of a use case for an application I am developing, I need to be able to take a "benchmark" string at runtime, and find the closest match from the XML file.
Please note that XML is not germane to the app and that I may go with SQL moving forward, but for today, I just needed an easy place to store the data and prove the concept.
I am using .NET 4.0, C#, forms app, LINQ, etc.
Question
How do I find the closest match? Hamming? Levenshtein? There are plenty of code samples online, but most are geared towards small string comparisons ("ant" vs. "aunt") or exact match. I will rarely have exact matches; I just need closest match.
Thanks in advance!
Matt
You mentioned using Levenhstein's Edit Distance and that your strings were about 3400 characters long.
I did a quick try and using the dynamic programming version of Levenhstein's Edit Distance it seems to be quite fast and cause no issue.
I did this:
final StringBuilder sb1 = new StringBuilder();
final StringBuilder sb2 = new StringBuilder();
final Random r = new Random(42);
final int n = 3400;
for (int i = 0; i < n; i++) {
sb1.append( (char) ('a' + r.nextInt(26)) );
sb2.append( (char) ('a' + r.nextInt(26)) );
}
final long t0 = System.currentTimeMillis();
System.out.println("LED: " + getLevenshteinDistance(sb1.toString(), sb2.toString()) );
final long te = System.currentTimeMillis() - t0;
System.out.println("Took: " + te + " ms");
And it's finding the distance in 215 ms on a Core 2 Duo from 2006 or so.
Would that work for you?
(btw I'm not sure I can paste the code for the DP LED implementation I've got here so you probably should search the Internet for one Java implementation)

Categories