I am trying to calculate the Fibonacci sequence in C# in a very simple way, however when it comes to the higher numbers it bugs out and stops working by giving out wrong answers.
ulong num = 1;
ulong lnum = 0;
uint x = 1;
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("(0) " + 1);
}
private void timer1_Tick(object sender, EventArgs e)
{
if (x <= 1000)
{
ulong newnum = lnum + num;
listBox1.Items.Add("(" + x + ") " + newnum);
listBox1.SetSelected((int)x, true);
lnum = num;
num = newnum;
x++;
}
}
I am making it in a way that I can watch it add up the numbers by adding them to a listbox 1 at a time.
ulong is too small for fibonacchi. You need to use something bigger. .NET 4 added BigInteger, that should allow for arbitrary number size.
For lower .NET versions, you need to find similliar 3rd party implementation
Related
I have been searching of a way to do this little exercise from my programming book, but I'm not able to think how to do this.
Here is what I have so far:
private void btnDisplay_Click(object sender, EventArgs e)
{
int numOrg = Convert.ToInt32(txtNumOrg.Text);
double numberToConvert = Convert.ToDouble(txtDailyIncrease.Text); // percent
double convertToDecimal = (numberToConvert / 100);
while (numOrg <= 10)
{
lstDisplay.Items.Add(numOrg + " " + convertToDecimal );
numOrg++;
}
}
For the values I am using: numOrg is 2 and numberToConvert is 30%.
The expected output should be: 2.6000, 3.3800, 4.3940, etc.
I just want to add an increase to my number each day. I definitely over complicated this simple task, but I've put 7 hours into this already and I'm not getting anywhere so I'm hoping someone can help me see this problem a little more clearly. Thanks in advance guys!
Please check this code:
static void Main(string[] args)
{
var numOrg = 2;
var percentage = 0.3;
var result = (double)numOrg;
while (numOrg <= 10)
{
result += percentage * result;
Console.WriteLine($"{numOrg}: {result}");
numOrg++;
}
Console.ReadKey();
}
It generates expected result:
2: 2,6
3: 3,38
4: 4,394
5: 5,7122
6: 7,42586
7: 9,653618
8: 12,5497034
9: 16,31461442
10: 21,208998746
I dont't know what exact logic is behind your code. Maybe you should loop from 1 to stop value and use numOrg only as value for calculations.
try this
private void btnDisplay_Click(object sender, EventArgs e)
{
int numOrg = Convert.ToInt32(txtNumOrg.Text);
double numberToConvert = double.Parse(txtDailyIncrease.Text); // percent
double convertToDecimal = (numberToConvert / 100);
var result = double.Parse(txtNumOrg.Text);
while (numOrg <= 10)
{
result += convertToDecimal * result;
lstDisplay.Items.Add(result);
numOrg++;
}
}
This question already has answers here:
How do I generate a random integer in C#?
(31 answers)
Closed 6 years ago.
I am wanting to generate a random number between 1 and 10. Yet I am getting a couple of errors.
public Form1()
{
InitializeComponent();
}
int randomNumber = (0, 11);
int attempts = 0;
public int RandomNumber
{
get
{
return randomNumber;
}
set
{
randomNumber = value;
}
}
it is all on the 0, 11 under the comma is says --> struct System.Int32 represents a 32-bit signed integer <--. Under the 11 it says --> Identifier expected Syntax error, ',' expected <--. Now if I just have like int randomNumber = 0; then it will work fine, still have multiple guesses and the guess count adds up like it should, and have the too high too low labels. just the number will always be 0.
Also how can I make it to where I don't have to click the guess button, I can just hit enter on the keyboard?
private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (int.Parse(textBox1.Text) > RandomNumber) label1.Text = "Too high.";
else if (int.Parse(textBox1.Text) < RandomNumber) label1.Text = "Too low.";
else
{
label1.Text = "You won.";
textBox1.Enabled = false;
label2.Text = "Attempts: 0";
textBox1.Text = String.Empty;
MessageBox.Show("You won in " + attempts + " attempts, press generate to play again.", "Winner!");
attempts = 0;
label2.Text = "Attempts: " + attempts.ToString();
return;
}
attempts++;
label2.Text = "Attempts: " + attempts.ToString();
}
catch { MessageBox.Show("Please enter a number."); }
}
To generate a Random number you have to usw the System.Random class. Your syntax can look something like this :
System.Random rng = new System.Random(<insert seed if you want>);
int randomNumber = rng.Next(1,11);
You have to do rng.Next(1,11) since the lower bound is include (1 is a possible result) and the upper bound is exclude (11 isnt getting added into the pool oft possible results).
To do implement your Enter shortcut you have to add a method to your Forms KeyPress event in which you call the button1_clicked method.
button1_Clicked_1(this, System.EventArgs.Empty);
At last you have to set your forms "KeyPreview" property to true.
You can use something like the below code to generate random number between 1 to 10
Random randomNumberGenrator = new Random();
int num = randomNumberGenrator.Next(10) + 1;
Take a look at this.
Use the Random class in order to generate a random number.
private Random _rnd = new Random();
private int RandomNumber
{
get
{
return _rnd.Next(0,11);
}
set
{
this = value;
}
}
i'm pretty new and i was wondering when if i press a butten a random number comes on but when that number is 2 there should be another textbox showing how many times it got 2.
without using if/else or switch
private void btnChoose_Click(object sender, EventArgs e)
{
double number2 = 0;
double When2 = 2;
Random number = new Random();
double chose = number.Next(1,7);
txtnumber.Text = chose.ToString();
txtnumber2.Text = something...
}
Solution: (it's not possible with the number 2 but it is with the number 6)
// global var
int number6 = 0;
private void btnChoose_Click(object sender, EventArgs e)
{
double When6 = 6;
Random number = new Random();
double chose = number.Next(1,7);
txtnumber.Text = chose.ToString();
number6 = Convert.toInt32(number6 + (chose/When6));
txtnumber6.Text = number6.ToString();
}
L.B's note: OP's comment at one of the deleted answer
it's a pretty anoying task and i just need to do this without the if/ese or switch
No array, no dictionary, no Linq, no built-in methods like Convert.ToIn32 etc. Only bit twiddling
Random number = new Random();
int TwosCount = 0;
private void btnChoose_Click(object sender, EventArgs e)
{
int chose = number.Next(1, 7);
TwosCount += ~((chose & 4) >> 2) & ((chose & 2) >> 1) & ~((chose & 1) >> 0);
txtnumber.Text = chose.ToString();
txtnumber2.Text = TwosCount.ToString();
}
PS: You can remove some unnecessary parentheses and write as:
~(chose & 4) >> 2 & (chose & 2) >> 1 & ~(chose & 1);
For a small range of random numbers such as this, (Random.Next(1,7) produces numbers from 1 to 6) you can use an array to keep track of how many times a number has come up. Make sure to declare this array inside of your main class, but outside of your button click method. Also, it doesn't look like you need to use floating point numbers for this job, so I've changed all the double variables to integers.
int[] numberCount = new int[6];
//if you really want to stay with doubles, then simply change the above line to this:
//double[] numberCount = new double[6];
private void btnChoose_Click(object sender, EventArgs e)
{
int number2 = 0;
//double When2 = 2; This line is not needed, so it's been commented out.
Random number = new Random();
int chose = number.Next(1,7);
numberCount[chose - 1]++; // Increment the amount of times we've seen this particular number
txtnumber.Text = chose.ToString();
txtnumber2.Text = numberCount[1].ToString(); // Display the amount of times we've seen the number 2
//Remember, array indexes are 0 based, so index 1 is actually the second number in the array, or number 2.
}
We can use this formula to find our index (Rnd -3)%2
when we subtract 3 from value, if its 2 or lower, it would get negative results as
1-3=-2 and -2%2=0
2-3=-1 and -1%2=-1
and other numbers results would be 0 or 1.
then we can add calculated value by one to start index from 0, now we have an array with three elements which the first element is number of occurrences of 2.
private readonly Random _random=new Random();
private readonly int [] numbers=new int[3];
private void button1_Click(object sender, EventArgs e)
{
var number = _random.Next(1,7);
var chose = number;
chose -= 3; //mod (2-3)=-1
chose %= 2;
chose++;
numbers[chose]++;
txtnumber.Text = number.ToString();
txtNumber2.Text = numbers[0].ToString();
}
Perhaps ;-)
double[] two = { 2 };
int count2 = 0;
private void btnChoose_Click(object sender, EventArgs e)
{
double chose = number.Next(1, 7);
txtnumber.Text = chose.ToString();
count2 = count2 + System.Convert.ToInt32(two.Contains(chose));
txtnumber2.Text = count2.ToString();
}
Random R = new Random();
void RUN()
{
int N = R.Next(2);
Action[] A = new Action[2];
A[0] = new Action(Act1);
A[1] = new Action(Act2);
A[N].Invoke();
}
private void Act2()
{
MessageBox.Show("Cancel");
}
private void Act1()
{
MessageBox.Show("OK");
}
this answer is without if/else/switch
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need some help with my program I built the simple dice program to show frequencies of the sum of two dice for 100 rolls. The program will read the file.
Now what i need is to declare an array that represents the possible results of throws of two dice,For each entry in the file, increment the element of the array corresponding to that result.Last, display the frequency count for that simulation. I do not know how to use an array in my program and need help trying to implement it into my program.
namespace Dice_Program
{
public partial class RollDice : Form
{
private int Dice1;
private int Dice2;
private int SUM;
const int Roll_MAX = 100;
private void btn_roll_Click(object sender, EventArgs e)
{
Random rand = new Random();
for (int lineNum = 1; lineNum <= Roll_MAX; lineNum++)
{
Dice1 = rand.Next(6) + 1;
Dice2 = rand.Next(6) + 1;
SUM = Dice1 + Dice2;
lstboxtotal.Items.Add(" On roll. " + lineNum + " You rolled a, " + Dice1 + " and a " + Dice2 + " for a sum of " + SUM);
}
}
private void btnwrite_Click(object sender, EventArgs e)
{ // Create a StreamWriter object
StreamWriter rollLog;
rollLog = File.CreateText ("Roll Results.txt"); // Creating the file
for (int count = 0; count <lstboxtotal.Items.Count; count++)
{
rollLog.WriteLine(Convert.ToString(lstboxtotal.Items[count]));
}
rollLog.Close(); // close file after creation
MessageBox.Show ("Your results have been successfully Saved to file.");
} // only first line is written 100 times
private void btnread_Click(object sender, EventArgs e)
{
using (StreamReader rollLog = new StreamReader("Roll Results.txt"))
{
while (rollLog.Peek() >= 0)
{
lstboxtotal.Items.Add(rollLog.ReadLine());
}
}
}
}
}
I'm having slight trouble understanding your english. But i think you want somthing like this.
(*Note this is kinda psudo code, and wont compile straight away, butim not going todo your homework)
int[] Rolls = { 0, 0, 0, 0, 0, 0 }; // 1 dice = 6 possible rolls 1- 6
void RollDice() {
int randomRoll = GetRandomDiceRoll(); //assume this returns 1-6 for the roll
//We use randomRoll-1 becuase the array is zero-indexed E.g. 0-5
Rolls[randomRoll-1]++;
//This increments the value and if the roll was 3 for instance your array will look like
// { 0, 0, 1, 0, 0, 0 }
}
Could someone please explain to me why my average keeps coming as 0 when I run my program? I have listed the entire code of my project on here and have literally never used arrays before. Also, is the name of this array mData? I tried reading in my book to determine what to look for in these items and have come up with nothing.
public partial class frmMain : Form
{
private const int mSize = 20;
private int[] mData = new int[mSize];
private int mIndex = 0;
private static void Main()
{
frmMain main = new frmMain();
Application.Run(main);
}
private frmMain()
{
InitializeComponent();
}
private void btnEnter_Click(object sender, EventArgs e)
{
int num;
num = int.Parse(txtInput.Text);
//store num in the array
mData[mIndex] = num;
mIndex = mIndex + 1;
//check for full array
if (mIndex == mSize)
{
//inform user that array is full
MessageBox.Show("The array is full.");
btnEnter.Enabled = false;
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
int n;
for (n = 0; n < mIndex; n++)
listBoxOutput.Items.Add(mData[n]);
}
private void btnAverage_Click(object sender, EventArgs e)
{
int sum = 0;
int average = 0;
if (mIndex == 0)
{
//inform user that array is empty
MessageBox.Show("The array is empty.");
}
//add up the values
for (int i = 0; i < mData.Length; i++)
{
sum += mData[i];
}
//divide by the number of values
average = sum / mSize;
listBoxOutput.Items.Add("The average of the array is: " + average);
}
}
One problem is that you are using ints. If the final value is a decimal less than 1, the int average will store 0. Changing average to a float will solve this. Also, you should not divide by mSize unless you know the entire array is filled. The user could insert one value, but it would be averaged with 19 0s.
since average, sum, and mSize are intergers, when you divide them, the result will be truncated.
average = sum / mSize;
so if sum/mSize is less than 1, average will always be equal to 0
to get average to have decimal points change the declaration to
double average = 0;
and the calculation to
average = (double)sum / (double)mSize;
Array has a built in property to calculate average which returns a decimal value as output. Example is below
int[] integer = new int[] { 1, 2, 3 };
Console.WriteLine(integer.Average().ToString());
Hope this helps.