public class Convert
{
public void MMtofeetfraction(float millimeters)
{
if ((millimeters % 304.8f) != 0)
{
int feet = (int)(millimeters / 304.8f);
double inchWithDecimal = millimeters * 0.03937;
string s = inchWithDecimal.ToString("0.0000");
string[] parts = s.Split('.');
int i1 = int.Parse(parts[0]);
float i2 = float.Parse("0." + parts[1]);
int inch = i1 % 12;
var accuracy = 16;
double num = 1;
double frac = i2 * accuracy;
num = Math.Round(frac);
if (num != 0)
{
while (num % 2 == 0)
{
num = num / 2;
accuracy = accuracy / 2;
}
if (inch != 0)
{
Debug.Log("Fraction output: " + feet + "'-" + inch + " " + num + "/" + accuracy + "\"");
}
else
{
Debug.Log("Fraction output: " + feet + "'-" + num + "/" + accuracy + "\"");
}
}
else
{
Debug.Log("Fraction output: " + feet + "'-" + inch + "\"");
}
}
else
{
Debug.Log("Fraction output: " + Math.Round(millimeters / 304.8) + "'");
}
}
}
Input 1440 : output : 4' 7 1/2"
Input 1550 : output : 5' 1 "
Input 1530 : output : 5' 1/4"
Now, this code works and gives output as needed. I was looking to improvise this code by removing string splitting and other string formatting. Can someone help with inbuilt functions to handle this?
Related
I am learning c# and I'm trying to make a program that calculate the champions winrate in (lol) League of Legends and I'm stuck with this problem:
The error is:
Error CS0136 A local or parameter named 'Result' cannot be declared in
this scope because that name is used in an enclosing local scope to
define a local or parameter
Here is my code:
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
double TeemoWinRate = 51.33;
double AkaliWinRate = 47.56;
double YasuoWinRate = 49.73;
double KhazixWinRate = 50.94;
double YoneWinRate = 47.84;
double LuxWinRate = 50.50;
double MorgWinRater = 50.83;
double TrandyWinRate = 48.50;
double GarenWinRate = 50.50;
double TeemoGold = 11.113;
double AkaliGold = 10.880;
double YasuoGold = 11.828;
double KhazixGold = 11.541;
double YoneGold = 11.650;
double LuxGold = 9.497;
double MorgGold = 8.990;
double TrandyGold = 12.182;
double GarenGold = 11.609;
double Te = TeemoWinRate;
double A = AkaliWinRate;
double Y = YasuoWinRate;
double K = KhazixWinRate;
double Yo = YoneWinRate;
double L = LuxWinRate;
double M = MorgWinRater;
double Tr = TrandyWinRate;
double G = GarenWinRate;
Console.WriteLine("Champions Ranked WinRate From the list below");
Console.WriteLine("Akali, " +
"Yasuo, " +
"Khazix, " +
"Yone, " +
"Lux, " +
"Morg, " +
"Trandy, " +
"Garen, " +
"Teemo.");
Console.WriteLine("Note: get sure that names are written as the list");
Console.Write("Enter Champion Name : ");
string Champion = Console.ReadLine();
//------------------------------First if stattement--------------------------------------------
if (Champion == "Akali")
{
Console.WriteLine("Akali WinRate is: " + AkaliWinRate + " " + "Total Gold: " + AkaliGold);
}
else if (Champion == "Yasuo")
{
Console.WriteLine("Yasuo WinRate is: " + YasuoWinRate + " " + "Total Gold: " + YasuoGold);
}
else if (Champion == "Khazix")
{
Console.WriteLine("Khazix WinRate is: " + KhazixWinRate + " " + "Total Gold: " + KhazixGold);
}
else if (Champion == "Yone")
{
Console.WriteLine("Yone WinRate is: " + YoneWinRate + " " + "Total Gold: " + YoneGold);
}
else if (Champion == "Lux")
{
Console.WriteLine("Lux WinRate is: " + LuxWinRate + " " + "Total Gold: " + LuxGold);
}
else if (Champion == "Morg")
{
Console.WriteLine("Morg WinRate is:" + MorgWinRater + " " + "Total Gold: " + MorgGold);
}
else if (Champion == "Trandy")
{
Console.WriteLine("Trandy WinRate is: " + TrandyWinRate + " " + "Total Gold: " + TrandyGold);
}
else if (Champion == "Garen")
{
Console.WriteLine("Garen WinRate is: " + GarenWinRate + " " + "Total Gold: " + GarenGold);
}
else if (Champion == "Teemo")
{
Console.WriteLine("Teemo WinRate is" + TeemoWinRate + " " + "Total Gold: " + TeemoGold);
}
else
{
Console.WriteLine("Please Enter the name Exactly as in the list.");
return;
}
Console.WriteLine("what champion do u want to Compare with other champs");
Console.WriteLine("Type " +
"\n 1 for (Teemo) " +
"\n 2 for (Akali) " +
"\n 3 for (Yasuo) " +
"\n 4 for (khazix) " +
"\n 5 for (Yone) " +
"\n 6 for (Lux)" +
"\n 7 for (Morg)" +
"\n 8 for (Trandy)" +
"\n 9 for (Garen)");
Console.Write("First Champion: ");
double Answer1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second Champion");
double Answer2 = Convert.ToInt32(Console.ReadLine());
//------------------------------Second if stattement--------------------------------------------
if (Answer1 == 1)
{
object Result = Answer1 - 1 + Te;
}
if (Answer1 == 2)
{
object Result = Answer1 - 2 + A;
}
if (Answer1 == 3)
{
object Result = Answer1 - 3 + Y;
}
if (Answer1 == 4)
{
object Result = Answer1 - 4 + K;
}
if (Answer1 == 5)
{
object Result = Answer1 - 5 + Yo;
}
if (Answer1 == 6)
{
object Result = Answer1 - 6 + L;
}
if (Answer1 == 7)
{
object Result = Answer1 - 7 + M;
}
if (Answer1 == 8)
{
object Result = Answer1 - 8 + Tr;
}
if (Answer1 == 9)
{
object Result = Answer1 - 9 + G;
}
//-----------------------------------Third if Statement--------------------------
if (Answer2 == 1)
{
object Result2 = Answer2 - 1 + Te;
}
if (Answer2 == 2)
{
object Result2 = Answer2 - 2 + A;
}
if (Answer2 == 3)
{
object Result2 = Answer2 - 3 + Y;
}
if (Answer2 == 4)
{
object Result2 = Answer2 - 4 + K;
}
if (Answer2 == 5)
{
object Result2 = Answer2 - 5 + Yo;
}
if (Answer2 == 6)
{
object Result2 = Answer2 - 6 + L;
}
if (Answer2 == 7)
{
object Result2 = Answer2 - 7 + M;
}
if (Answer2 == 8)
{
object Result2 = Answer2 - 8 + Tr;
}
if (Answer2 == 9)
{
object Result2 = Answer2 - 9 + G;
}
}
}
}
The error says that you cannot use Result since it is being used somewhere else try renaming it.
This question already has answers here:
Rule of thumb to test the equality of two doubles in C#?
(6 answers)
How should I compare these doubles to get the desired result?
(7 answers)
Arithmetic error when adding two double values [duplicate]
(3 answers)
Closed 3 years ago.
This program bring to random numbers in a decimal way to get sum using ran.next and are stored in the variables sum1a (for the first number) and sum2a (for the second number) and printed in "Suma1.Text"; the operator need to captured the result in the textbox called "Resultado" how has the name "Resultado1" and stored in the variable result1, then is compared with the sum of sum1a and sum2a and stored in total1 to get compared with result1, if total1 match with result1 have to print "Correcto" or "Incorrecto" when there is no match, but sometimes even when the result is correct said that is "Incorrecto".
[Calculator vs Program][1]
namespace Sumas_punto_decimal_prueba
{
public partial class Form1 : Form
{
double sum1a, sum2a;
string num1a, num2a;
double total1;
double result1;
public Form1()
{
InitializeComponent();
}
private void Generar_Click(object sender, EventArgs e)
{
//LIMPIADOR
foreach (Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
TextBox text = ctrl as TextBox;
text.Clear();
}
}
Random ran = new Random();
//SUMA 1
sum1a = ran.Next(100 , 10000) / 100.00;
sum2a = ran.Next(100 , 10000) / 100.00;
num1a = sum1a.ToString("##.#0");
num2a = sum2a.ToString("##.#0");
if (sum1a < 10 && sum2a < 10)
{
Suma1.Text = " 0" + num1a + "\r\n +0" + num2a + "\r\n¯¯¯¯¯¯¯";
}
else if (sum1a < 1 && sum2a < 1)
{
Suma1.Text = " 00" + num1a + "\r\n +00" + num2a + "\r\n¯¯¯¯¯¯¯";
}
else if (sum1a < 10 && sum2a < 1)
{
Suma1.Text = " 0" + num1a + "\r\n +00" + num2a + "\r\n¯¯¯¯¯¯¯";
}
else if (sum1a < 1 && sum2a < 10)
{
Suma1.Text = " 00" + num1a + "\r\n +0" + num2a + "\r\n¯¯¯¯¯¯¯";
}
else if (sum1a < 10)
{
Suma1.Text = " 0" + num1a + "\r\n +" + num2a + "\r\n¯¯¯¯¯¯¯";
}
else if (sum1a < 1)
{
Suma1.Text = " 00" + num1a + "\r\n +" + num2a + "\r\n¯¯¯¯¯¯¯";
}
else if (sum2a < 10)
{
Suma1.Text = " " + num1a + "\r\n +0" + num2a + "\r\n¯¯¯¯¯¯¯";
}
else if (sum2a < 1)
{
Suma1.Text = " " + num1a + "\r\n +00" + num2a + "\r\n¯¯¯¯¯¯¯";
}
else if (sum2a < 1)
{
Suma1.Text = " " + num1a + "\r\n +00" + num2a + "\r\n¯¯¯¯¯¯¯";
}
else
{
Suma1.Text = " " + num1a + "\r\n +" + num2a + "\r\n¯¯¯¯¯¯¯";
}
}
private void Calificar_Click(object sender, EventArgs e)
{
//SUMA NUMERO 1
double.TryParse(Resultado1.Text, out result1);
total1 = sum1a + sum2a;
if (result1 == total1)
{
Validacion1.Text = "Correcto";
}
else
{
Validacion1.Text = "Incorrecto. \r\nEl resultado es: " + total1;
}
}
}
}
What can be the reason that sometimes that error happen? I make a stimated and happen 1 of 15 times.
Thank to all for the help but already found a solution, using Math.Round() and "Zero placeholder"
sum1a = ran.Next(10000) / 100.00;
sum2a = ran.Next(10000) / 100.00;
sum1a = Math.Round(sum1a, 2, MidpointRounding.AwayFromZero);
sum2a = Math.Round(sum2a, 2, MidpointRounding.AwayFromZero);
num1a = sum1a.ToString("00.00");
num2a = sum2a.ToString("00.00");
Suma1.Text = " " + num1a + "\r\n +" + num2a + "\r\n¯¯¯¯¯¯¯";
Thanks. uwu
Probably because they don't even equal at all,
Probably not all the numbers were captured in. Compare
The strings instead and use print action to see where the error is at
if (string == string)
{
// Ganastes!
}
if("159.73" == "159.73")
{
// Correct!
}
IN C# i am trying to solve a problem :
Write a program that checks whether the product of the odd elements is equal to the product of the even elements.
The only thing left is:
On the second line you will receive N numbers separated by a whitespace.
I am unable to get this working. I have tried with Split but it keeps breaking. Can someone help?
Example:
Input
5
2 1 1 6 3
Output
yes 6
static void Main(string[] args)
{
long N = long.Parse(Console.ReadLine());
long[] array = new long[N];
long ODD = 1;
long EVEN = 1;
for (int i = 0; i < N; i++)
{
array[i] = int.Parse(Console.ReadLine());
if ((i + 1) % 2 == 0)
{
EVEN *= array[i];
}
else
{
ODD *= array[i];
}
}
if (EVEN == ODD)
{
Console.WriteLine("yes" + " " +
ODD);
}
else
{
Console.WriteLine("no" + " " + ODD + " " + EVEN);
}
}
Read from console input and keep it to an string array, Then convert each array element to long and apply the Odd Even logic like below:
static void Main(string[] args)
{
string input = Console.ReadLine();
string[] inputArray = input.Split(' ');
long element;
long odd = 1;
long even = 1;
foreach (var i in inputArray)
{
element = long.Parse(i);
if (element % 2 == 0)
{
even *= element;
}
else
{
odd *= element;
}
}
Console.WriteLine("\nOdd product = " + odd + ", Even product = " + even);
if (odd == even)
{
Console.WriteLine("ODD == EVEN \n");
Console.WriteLine("Yes" + " " + odd);
}
else
{
Console.WriteLine("ODD != EVEN \n");
Console.WriteLine("No" + " " + odd + " " + even);
}
Console.ReadKey();
}
long[] nums = input.Split(' ').Select(x => long.Parse(x))..ToArray(); //split numbers by space and cast them as int
int oddProduct = 1, evenProduct = 1; // initial values
foreach(long x in nums.Where(a => a%2 == 1))
oddProduct *= x; // multiply odd ones
foreach(long x in nums.Where(a => a%2 == 0))
evenProduct *= x; // multiply even ones
I have an EventBox in my application for handling notify events (enternotify, motionNotify and LeaveNotify are the interestin events for me). Inside this EventBox is an HScale, for which I display tooltips depending on the mouse position for audio seeking. But the motion nofity event doesn't get fired.
Some code:
protected void ebAudiofileSeekerEnterNotifyEvent (object o, EnterNotifyEventArgs args)
{
log.debug("ebAudiofileSeekerEnterNotifyEvent called");
int x = -1;
int y = -1;
int intX = -1;
int intY = -1;
int originX;
int originY;
this.GetPosition(out originX, out originY);
Gdk.ModifierType modifierType = Gdk.ModifierType.None;
this.Screen.RootWindow.GetPointer(out x, out y, out modifierType);
this.hsAudiofileSeeker.TranslateCoordinates(this,this.hsAudiofileSeeker.Allocation.X,this.hsAudiofileSeeker.Allocation.Y,out intX,out intY);
double valueAtPos = ((x - (intX + originX)) / (this.hsAudiofileSeeker.Allocation.Width * 1.0)) * this.hsAudiofileSeeker.Adjustment.Upper * 1.0;
long ticksAtPosition = (this.objProgram.getAudioManager().getDuration().Ticks * (long)valueAtPos) / 100;
TimeSpan timeSpanAtPosition = TimeSpan.FromTicks(ticksAtPosition);
this.lblTooltipAudiofileSeeker.Text = (timeSpanAtPosition.Hours > 9 ? timeSpanAtPosition.Hours.ToString() : "0" + timeSpanAtPosition.Hours.ToString()) + ":" + (timeSpanAtPosition.Minutes > 9 ? timeSpanAtPosition.Minutes.ToString() : "0" + timeSpanAtPosition.Minutes.ToString()) + ":" + (timeSpanAtPosition.Seconds > 9 ? timeSpanAtPosition.Seconds.ToString() : "0" + timeSpanAtPosition.Seconds.ToString());
this.hsAudiofileSeeker.TooltipWindow.Move(x, intY + originY);
this.hsAudiofileSeeker.TooltipWindow.ShowAll();
}
protected void ebAudiofileSeekerMotionNotifyEvent (object o, MotionNotifyEventArgs args)
{
log.debug("ebAudiofileSeekerMotionNotifyEvent called");
int x = -1;
int y = -1;
int intX = -1;
int intY = -1;
int originX;
int originY;
this.GetPosition(out originX, out originY);
Gdk.ModifierType modifierType = Gdk.ModifierType.None;
this.Screen.RootWindow.GetPointer(out x, out y, out modifierType);
this.hsAudiofileSeeker.TranslateCoordinates(this,this.hsAudiofileSeeker.Allocation.X,this.hsAudiofileSeeker.Allocation.Y,out intX,out intY);
double valueAtPos = ((x - (intX + originX)) / (this.hsAudiofileSeeker.Allocation.Width * 1.0)) * this.hsAudiofileSeeker.Adjustment.Upper * 1.0;
long ticksAtPosition = (this.objProgram.getAudioManager().getDuration().Ticks * (long)valueAtPos) / 100;
TimeSpan timeSpanAtPosition = TimeSpan.FromTicks(ticksAtPosition);
this.lblTooltipAudiofileSeeker.Text = (timeSpanAtPosition.Hours > 9 ? timeSpanAtPosition.Hours.ToString() : "0" + timeSpanAtPosition.Hours.ToString()) + ":" + (timeSpanAtPosition.Minutes > 9 ? timeSpanAtPosition.Minutes.ToString() : "0" + timeSpanAtPosition.Minutes.ToString()) + ":" + (timeSpanAtPosition.Seconds > 9 ? timeSpanAtPosition.Seconds.ToString() : "0" + timeSpanAtPosition.Seconds.ToString());
this.hsAudiofileSeeker.TooltipWindow.Move(x, intY + originY);
}
protected void ebAudiofileSeekerLeaveNotifyEvent (object o, LeaveNotifyEventArgs args)
{
log.debug("ebAudiofileSeekerLeaveNotifyEvent called");
this.hsAudiofileSeeker.TooltipWindow.HideAll();
}
The ebAudiofileSeekerMotionNotifyEvent and ebAudiofileSeekerLeaveNotifyEvent work, but not the motion event, any ideas why? I'm a bit confused.
Thanks for your help.
Did you turn off event compression? Tooltips turn on POINTER_MOTION_HINT_MASK which messes with event compression.
I came accross this, setting the ebAudiofileSeeker AboveChild property to true and added the following code for the listeners:
protected void ebAudiofileSeekerEnterNotifyEvent (object o, EnterNotifyEventArgs args)
{
log.debug("ebAudiofileSeekerEnterNotifyEvent called");
if (Program.getInstance().getAudioManager().Duration > TimeSpan.Zero)
{
int x = -1;
int y = -1;
int intX = -1;
int intY = -1;
int originX;
int originY;
this.GetPosition(out originX, out originY);
Gdk.ModifierType modifierType = Gdk.ModifierType.None;
this.Screen.RootWindow.GetPointer(out x, out y, out modifierType);
this.hsAudiofileSeeker.TranslateCoordinates(this, this.hsAudiofileSeeker.Allocation.X, this.hsAudiofileSeeker.Allocation.Y, out intX, out intY);
double valueAtPos = ((x - (intX + originX)) / (this.hsAudiofileSeeker.Allocation.Width * 1.0)) * this.hsAudiofileSeeker.Adjustment.Upper * 1.0;
long ticksAtPosition = (Program.getInstance().getAudioManager().Duration.Ticks * (long)valueAtPos) / 100;
TimeSpan timeSpanAtPosition = TimeSpan.FromTicks(ticksAtPosition);
this.lblTooltipAudiofileSeeker.Text = (timeSpanAtPosition.Hours > 9 ? timeSpanAtPosition.Hours.ToString() : "0" + timeSpanAtPosition.Hours.ToString()) + ":" + (timeSpanAtPosition.Minutes > 9 ? timeSpanAtPosition.Minutes.ToString() : "0" + timeSpanAtPosition.Minutes.ToString()) + ":" + (timeSpanAtPosition.Seconds > 9 ? timeSpanAtPosition.Seconds.ToString() : "0" + timeSpanAtPosition.Seconds.ToString());
this.hsAudiofileSeeker.TooltipWindow.Move(x, intY + originY);
this.hsAudiofileSeeker.TooltipWindow.ShowAll();
}
}
protected void ebAudiofileSeekerMotionNotifyEvent (object o, MotionNotifyEventArgs args)
{
log.debug("ebAudiofileSeekerMotionNotifyEvent called");
if (Program.getInstance().getAudioManager().Duration > TimeSpan.Zero)
{
int x = -1;
int y = -1;
int intX = -1;
int intY = -1;
int originX;
int originY;
this.GetPosition(out originX, out originY);
Gdk.ModifierType modifierType = Gdk.ModifierType.None;
this.Screen.RootWindow.GetPointer(out x, out y, out modifierType);
this.hsAudiofileSeeker.TranslateCoordinates(this, this.hsAudiofileSeeker.Allocation.X, this.hsAudiofileSeeker.Allocation.Y, out intX, out intY);
double valueAtPos = ((x - (intX + originX)) / (this.hsAudiofileSeeker.Allocation.Width * 1.0)) * this.hsAudiofileSeeker.Adjustment.Upper * 1.0;
log.debug("modifier = " + modifierType);
if (modifierType.HasFlag(Gdk.ModifierType.Button1Mask))
{
log.debug("modifier is button 1, so change value");
this.hsAudiofileSeeker.Value = valueAtPos;
}
long ticksAtPosition = (Program.getInstance().getAudioManager().Duration.Ticks * (long)valueAtPos) / 100;
TimeSpan timeSpanAtPosition = TimeSpan.FromTicks(ticksAtPosition);
this.lblTooltipAudiofileSeeker.Text = (timeSpanAtPosition.Hours > 9 ? timeSpanAtPosition.Hours.ToString() : "0" + timeSpanAtPosition.Hours.ToString()) + ":" + (timeSpanAtPosition.Minutes > 9 ? timeSpanAtPosition.Minutes.ToString() : "0" + timeSpanAtPosition.Minutes.ToString()) + ":" + (timeSpanAtPosition.Seconds > 9 ? timeSpanAtPosition.Seconds.ToString() : "0" + timeSpanAtPosition.Seconds.ToString());
this.hsAudiofileSeeker.TooltipWindow.Move(x, intY + originY);
}
}
protected void ebAudiofileSeekerLeaveNotifyEvent (object o, LeaveNotifyEventArgs args)
{
log.debug("ebAudiofileSeekerLeaveNotifyEvent called");
this.hsAudiofileSeeker.TooltipWindow.HideAll();
}
The code can be found here: http://sourceforge.net/p/audiocuesheet/code/HEAD/tree/
I was able to solve the Collatz conjecture algorithm (no, i didn't try to prove it) in about 5 minutes using Java.
Now that I'm learning C# to make web apps, I'm running into trouble doing the same thing.
I simply want the user to enter a number, click a button, and print the output to a text box.
Here is the button Click event handler method I'm using:
protected void Button3_Click(object sender, EventArgs e)
{
string x = TextBox1.Text; //user entered a number
string y =collatz(x); //this function is below and returns a string
chatbox.Text = y; //output
}
And here is the Collatz method:
public static string collatz(string y)
{
if (y == null)
return null;
double x = double.Parse(y); //x is my "n"
y = x.ToString(); //output string
double large = x; //keep track of biggest number
// the algorithm
// the redundancies (like x==1.. x!= 1) are part of troubleshooting :/
while (x > 1)
{
if (x % 2 == 0)
{
x = x / 2;
if (x > large)
large = x;
if (x != 1)
y = y+" "+ x.ToString();
if (x == 1)
{
y = y + " " + x.ToString();
y = y + " largest number was " + large;
}
}
if (x % 2 != 0)
{
if (x == 1)
{
y = y+" "+ x.ToString();
y = y + " largest number was " + large;
}
x = (3 * x) + 1;
if (x > large)
large = x;
y = y+" "+ x.ToString();
}
}
return y;
}
EDIT
when I use the VS.net debugger and enter a number like 2, I get NO output and NO error. I'm just left waiting forever. If it were an infinite loop, I would get an error eventually, right?
and no, this is not a homework problem (it was 2 years ago when I did it in JAVA though :).) I'm learning C# independently.
You had an infinite loop. Try this:
public static string collatz(string y)
{
if (y == null)
{
return null;
}
int x = int.Parse(y); //x is my "n"
var results = new StringBuilder();
results.Append(x.ToString());
int largest = x; //keep track of biggest number
// the algorithm
// the redundancies (like x==1.. x!= 1) are part of troubleshooting :/
while (x > 1)
{
if (x % 2 == 0)
{
x = x / 2;
if (x > largest)
{
largest = x;
}
if (x != 1)
{
results.Append(" " + x.ToString());
}
if (x == 1)
{
results.Append(" " + x.ToString());
results.Append(" largest number was " + largest.ToString());
return results.ToString();
}
}
if (x % 2 != 0)
{
if (x == 1)
{
results.Append(" " + x.ToString());
results.Append(" largest number was " + largest.ToString());
return results.ToString();
}
x = (3 * x) + 1;
if (x > largest)
{
largest = x;
}
results.Append(" " + x.ToString());
}
}
return results.ToString();
}
Two notes:
When you're doing string concatenation in a loop, it's a good habit to use a StringBuilder rather than s = s + t. Lots, lots less memory allocations.
A lot of times you can't rely on == when it comes to double values. It seems to work in this case, but it might not when you get to higher numbers where there's less precision. Since all the numbers are going to be int's anyway, might as well use those.
if (x == 1)
{
y = y+" "+ x.ToString();
y = y + " largest number was " + large;
}
This part here (odd x) is redundant. For if x is 1, it will never enter the while loop. Your code seems logically. Maybe try using integer instead.
x = x / 2;
if (x > large)
large = x;
Redundant code again for even x part. How do you expect x to be bigger than large after division by 2? Just check it in the 3n+1 part will do.
if (x == 1)
{
y = y + " " + x.ToString();
y = y + " largest number was " + large;
}
You can just leave this part out and let the while loop handle this check.
public static string collatz(string y)
{
if (y == null)
return null;
double x = double.Parse(y);
y = x.ToString();
double large = x;
while (x > 1) {
if (x % 2 == 0) {
x = x / 2; // x reassigned
if (x > large)
large = x;
if (x != 1)
y = y + " " + x.ToString();
if (x == 1) {
y = y + " " + x.ToString();
y = y + " largest number was " + large;
}
}
// Infinite loop goes because of that
if (x % 2 != 0) { // double check on reassigned variable, use “else” instead
if (x == 1) {
y = y + " " + x.ToString();
y = y + " largest number was " + large;
}
x = (3 * x) + 1;
if (x > large)
large = x;
y = y + " " + x.ToString();
}
}
return y;
}
I tried it with fixed code (using else) and it works fine.
Also, you don't need double type since Collatz works with natural numbers. The following is a quick refactoring to add more .NET-ty to your code:
public static string collatz(string input)
{
int current = 0;
if (string.IsNullOrEmpty(input) || !int.TryParse(input, out current) || current < 1) {
return "Empty, not a number or less then 1";
}
int max = current;
while (current > 1) {
if (current % 2 == 0) {
current = current / 2; // current reassigned
if (current > max)
max = current;
if (current != 1)
input = input + " " + current.ToString();
if (current == 1) {
input = input + " " + current.ToString();
input = input + " largest number was " + max;
}
} else {
if (current == 1) {
input = input + " " + current.ToString();
input = input + " largest number was " + max;
}
current = (3 * current) + 1;
if (current > max)
max = current;
input = input + " " + current.ToString();
}
}
return input;
}
View Equation:
if the number is even: n/2
if the number is odd: 3n+1
Step One:
Add a method called Collazt which returns a collection of objects of type int of class List<?>
public static List<int> Collazt(int n) {
List<int> data = new List<int>();
data.Add(n);
int resul = 0;
while (true) {
if (n == 1) {
break;
}
if ((n % 2) == 0)
{
resul = n / 2;
n = resul;
}
else {
resul = (n * 3) + 1;
n = resul;
}
data.Add(n);
}
return data;
}
Step Two:
We call the method in our main class.
static void Main(string[] args)
{
Console.Write("N: ");
int r = int.Parse(Console.ReadLine());
List<int> result = Collazt(r);
Console.WriteLine("Lista:");
Console.WriteLine("[");
for (int i= 0; i<result.Count; i++) {
Console.Write(result[i]+"\n");
}
Console.WriteLine("]");
}
string restart;
do
{
Console.WriteLine("Type a Whole Number");
double n = Convert.ToDouble(Console.ReadLine());
do
{double a = n;
if (n % 2 == 0)
{
Console.WriteLine("Even");
n = a / 2;
Console.WriteLine(n);
}
else
{
Console.WriteLine("Odd");
n = (3*a) + 1;
Console.WriteLine(n);
}
}
while (n != 1);
Console.WriteLine("Yo Wanna Restart? Type y and press enter");
restart = Console.ReadLine();
Console.Clear();
}
while (restart == "y");
Console.ReadKey(true);
(not a professional programmer, made it for fun, i know there are better ways)