private void multiBtn_Click(object sender, EventArgs e)
{
for (int a = 1; a <= 10; a++)
for (int b = 1; b <= 10; b++)
lblTable.Text = (a + " * " + b + " = " + (a * b));
for (int a = 1; a <= 10; a++)
for (int b = 1; b <= 10; b++)
lblTable.Text += (a + " * " + b + " = " + (a * b));
}
It's doing exactly what I want it to do when it comes to multiplying. It's just not lined up in rows. It prints out the multiplication for integers 1 to 10. I just need them in rows and columns, could anyone explain to me how to do that through a label. really don't know how to explain what it's doing but in my gui it prints out like "10*10=1001*1=11*2=21*3=3" and so on it just keeps going like that. I'm not even sure why it starts out with 10*10=100
Try using the newline character, which will put each item on a new row. For columns, it is a little trickier. Using a fixed width font and some padding around the numbers should do.
First, the newline code addition:
lblTable.Text += (a + " * " + b + " = " + (a * b) + "\n");
Or, a preferred format for many is to use string.Format for the string:
lblTable.Text += (string.Format("{0} * {1} = {2}\n", a, b, (a * b)));
To get them to align, you can use the PadLeft string method. In the example below, I am assuming that a and b will have less than or equal to two digits, and a * b will have less than or equal to 3 digits (remember this will only work if you use a fixed-width font, like Consolas):
for (int a = 1; a <= 10; a++)
{
for (int b = 1; b <= 10; b++)
{
lblTable.Text += (string.Format("{0} * {1} = {2}\n",
a.ToString().PadLeft(2),
b.ToString().PadLeft(2),
(a * b).ToString().PadLeft(3)));
}
}
It's pretty unclear what it is exactly you want. But note that you can insert newline characters between each line (Environment.NewLine) to force a line-break, to have text displayed on successive rows (lines) in the Label.
For example:
lblTable.Text += a + " * " + b + " = " + (a * b) + Environment.NewLine;
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I just learned how to use if and tried to do a simple calculator. but the code is way too long and i want to add more options to it, can i make it any shorter using any other method?
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many numbers do you wish to calculate? ");
string HowMany = Console.ReadLine();
if (HowMany == "2") {
Console.Write("Enter #1: ");
int x = int.Parse(Console.ReadLine());
Console.Write("Enter #2: ");
int y = int.Parse(Console.ReadLine());
int sum = x + y; int sub = x - y; int mult = x * y; int div = x / y;
Console.WriteLine("The Result : Sum = " + sum + " Sub = " + sub + " Mult = " + mult + " Div = " + div); }
else if (HowMany == "3") {
Console.Write("Enter #1: ");
int x = int.Parse(Console.ReadLine());
Console.Write("Enter #2: ");
int y = int.Parse(Console.ReadLine());
Console.Write("Enter #3: ");
int z = int.Parse(Console.ReadLine());
int sum = x + y + z; int sub = x - y - z; int mult = x * y * z; int div = x / y / z;
Console.WriteLine("The Result : Sum = " + sum + " Sub = " + sub + " Mult = " + mult + " Div = " + div); }
else if (HowMany == "4")
{
Console.Write("Enter #1: ");
int x = int.Parse(Console.ReadLine());
Console.Write("Enter #2: ");
int y = int.Parse(Console.ReadLine());
Console.Write("Enter #3: ");
int z = int.Parse(Console.ReadLine());
Console.Write("Enter #4: ");
int w = int.Parse(Console.ReadLine());
int sum = x + y + z + w; int sub = x - y - z - w; int mult = x * y * z * w; int div = x / y / z / w;
Console.WriteLine("The Result : Sum = " + sum + " Sub = " + sub + " Mult = " + mult + " Div = " + div);
}
Console.ReadKey();
}
}
}
This does just the sum. I'll leave handling the other calculations to you.
int sum = 0;
for(int i = 1;i<=HowMany;i++)
{
Console.Write("Enter #{0}: ", i);
int input = int.Parse(Console.ReadLine());
sum += input;
}
Console.WriteLine("The Result : Sum = {0}", sum);
using System.IO;
using System;
class Program {
static void Main() {
Console.WriteLine("How many numbers do you wish to calculate? ");
string HowMany = Console.ReadLine();
int[] nums = new int[int.Parse(HowMany)];
int sum = 0, sub = 0, mult = 1, div = 1;
for (int i = 0; i < int.Parse(HowMany); i++) {
Console.Write("Enter #" + (i + 1) + ": ");
nums[i] = int.Parse(Console.ReadLine());
sum += nums[i];
sub -= nums[i];
mult *= nums[i];
div /= nums[i];
}
Console.WriteLine("The Result : Sum = " + sum + " Sub = " + sub + " Mult = " + mult + " Div = " + div);
Console.ReadKey();
}
}
You can just use a loop, and keep a rolling total of the values. Also, I changed div to be a double, because integer division is really boring - it's nice to see the decimal value:
I also made it so the user can only enter an integer greater than zero for the quantity of numbers they want to calculate.
And finally, they can only enter a non-zero integer for the number, because a zero input means we have to do some check for that during division, the multiplication value will always be zero, and it does nothing to the addition and subtraction totals.
Console.Write("How many numbers do you wish to calculate? ");
int count;
while (!int.TryParse(Console.ReadLine(), out count) || count < 1)
{
Console.Write("Error: enter a positive, whole number: ");
}
int input, sum = 0, sub = 0, mult = 0;
double div = 0;
for (int i = 1; i <= count; i++)
{
Console.Write($"Enter #{i}: ");
// Don't allow user to enter 0. It does nothing to the addition or subtraction
// values, will make the multiplication value zero, and cannot be use for division
while (!int.TryParse(Console.ReadLine(), out input) || input == 0)
{
Console.Write("Error: enter a non-zero whole number: ");
}
if (i == 1)
{
// On the first input, we just store the number
sum = sub = mult = input;
div = input;
}
else
{
sum += input;
sub -= input;
mult *= input;
div /= input;
}
}
Console.WriteLine("The Result : Sum = " + sum + " Sub = " +
sub + " Mult = " + mult + " Div = " + div);
Console.ReadKey();
I made [Hashtable hash] such as
hash(i, 1)
hash(j, 2)
Also I made an [arraylist sArray] which include "i" or "j" such as
sArray[0] : hello
sArray[1] : first number is i
sArray[2] : second number is j
sArray[3] : bye
Now, I want to change the "i" and "j" in the sArray to the values of the hash.
How can I do it?
If I understand properly, I think this is the code in c#
//Your example
int i = 1;
int j = 2;
var hash = new System.Collections.Hashtable();
hash[i] = -173.5;
hash[j] = 37;
var sArray = new System.Collections.ArrayList();
sArray.Add("hello");
sArray.Add("first number is " + hash[i].ToString());
sArray.Add("second number is " + hash[j].ToString());
sArray.Add("bye");
// more general, you could have different i and j position
i = 3;
j = 4;
hash[i] = 33.3;
hash[j] = -44.4;
sArray[1] = "number in " + i.ToString() + " position is " + hash[i].ToString();
sArray[2] = "number in " + j.ToString() + " position is " + hash[j].ToString();
// I think following option is more easy to read and fast if iterated
i = 5;
j = 6;
hash[i] = 55.5;
hash[j] = -66.6;
sArray[1] = String.Format("number in {0} position is {1}", i, hash[i]);
sArray[2] = String.Format("number in {0} position is {1}", j, hash[j]);
Basically I have a graph that is bound from a DataTable which source is from a DataGridView. I have zoomable functions on the graph and I need it use X Axis SelectionStart and SelectionEnd in order to calculate the block of data that is selected.
So I have some minimums maximums and averages placed in a richtextbox on another tab. As shown below in the code:
//To show the Data from file into the TextBox
richTextBox1.AppendText("\n" + "Heart Average : " + HRM.Active.DataRows.Average(r => r.HeartRate) + "\n");
richTextBox1.AppendText("\n" + "Heart Minimum : " + HRM.Active.DataRows.Min(r => r.HeartRate) + "\n");
richTextBox1.AppendText("\n" + "Heart Maximum : " + HRM.Active.DataRows.Max(r => r.HeartRate) + "\n");
richTextBox1.AppendText("\n" + "Average Speed (KM/H): " + HRM.Active.DataRows.Average(r => r.Speed) + "\n");
richTextBox1.AppendText("\n" + "Maximum Speed : " + HRM.Active.DataRows.Max(r => r.Speed) + "\n");
richTextBox1.AppendText(Environment.NewLine + " - (MPH): " + "");
richTextBox1.AppendText("\n" + "Average Power: " + HRM.Active.DataRows.Average(r => r.Power) + "\n");
richTextBox1.AppendText("\n" + "Maximum Power : " + HRM.Active.DataRows.Max(r => r.Power) + "\n");
richTextBox1.AppendText("\n" + "Average Altitude (KM/H): " + HRM.Active.DataRows.Average(r => r.Altitude) + "\n");
richTextBox1.AppendText("\n" + "Maximum Altitude : " + HRM.Active.DataRows.Max(r => r.Altitude) + "\n");
richTextBox1.AppendText("\n" + "Cadence Average : " + HRM.Active.DataRows.Average(r => r.Cadence) + "\n");
richTextBox1.AppendText("\n" + "Cadence Maximum : " + HRM.Active.DataRows.Max(r => r.Cadence) + "\n");
richTextBox1.AppendText("\n" + "Pressure Average : " + HRM.Active.DataRows.Average(r => r.Pressure) + "\n");
richTextBox1.AppendText("\n" + "Pressure Maximum : " + HRM.Active.DataRows.Max(r => r.Pressure) + "\n");
Now in the image below you can see the image of the Graph and the data it shows on there, Here is the code which binds the datatable to the graph.
protected void drawChart()
{
DataTable dt = new DataTable();
dt.Clear();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
Now what I need to do is have another textbox near the Graph and every time I zoom and the grey block comes out it displays the minimums maximiums and averages for the block i have selected! Then when I zoom out it resets to the original.
If you do not understand what I mean just message me and I will give more information.
To update a statistical calculation based on the visible Points after zooming or scrolling you need know two things: When should you do it and which points are visible.
The event to use is AxisViewChanged, that's easy. After you have hooked it up you can call a function to update your statistics:
private void chart1_AxisViewChanged(object sender, ViewEventArgs e)
{
updateStats();
}
The difficult part is to know which portion of the Points collection is visible.
At first glance you may think that the ViewEventArgs parm helps; after all it has such promising data as: NewPosition and NewSize.
But looking closer you will see that both are doubles, so unless your XValues have been set counting up from 0 by 1, they won't index into the Points collection.
Instead we must do a little searching for those values, from left for the minimum and from the right for the maximum. Here is a function to do so:
int getVisiblePoint(Chart chart, Series series, bool first)
{
Series S = series;
ChartArea CA = chart.ChartAreas[S.ChartArea];
DataPoint pt = null;
if (first) pt = S.Points.Select(x => x)
.Where(x => x.XValue >= CA.AxisX.ScaleView.ViewMinimum)
.DefaultIfEmpty(S.Points.First()).First();
else pt = S.Points.Select(x => x)
.Where(x => x.XValue <= CA.AxisX.ScaleView.ViewMaximum)
.DefaultIfEmpty(S.Points.Last()).Last();
return S.Points.IndexOf(pt);
}
From here on things get a lot easier; we can do statistics on our series, maybe like this:
void updateStats()
{
int firstPt = getVisiblePoint(chart1, chart1.Series[0], true);
int lastPt = getVisiblePoint(chart1, chart1.Series[0], false);
int sCount = chart1.Series.Count;
double[] avg = new double[sCount];
double[] min = new double[sCount];
double[] max = new double[sCount];
for (int i = 0; i < sCount; i++)
{
Series S = chart1.Series[i];
avg[i] = getAverage(S, firstPt, lastPt);
min[i] = getMixMax(S, firstPt, lastPt, true);
max[i] = getMixMax(S, firstPt, lastPt, false);
}
// insert code to display the data here!
}
using simple functions to do the math:
double getAverage(Series series, int first, int last)
{
double sum = 0;
for (int i = first; i < last; i++) sum += series.Points[i].YValues[0];
return sum / (last - first + 1);
}
double getMixMax(Series series, int first, int last, bool min)
{
double val = 0;
for (int i = first; i < last; i++)
{
double v = series.Points[i].YValues[0];
if ( (min && val > v) || (!min && val >= v)) val = v;
}
return val;
}
How do I exclude and count values which are bigger than 4095 from this array:
EDIT: so this is the final code I have, it basically works on some mousepoints, however there are some exceptions where the difference between depth and neighbouring values are too big (see green marked box on http://s7.directupload.net/images/131007/uitb86ho.jpg). In the screenshot there is a red box, which contains 441 Pixels, and the average value of those 441 Pixels is 1198 mm, where the depth on x;y 15;463 is only about 614 mm. Have no idea where the bigger average values come from, since it should have been excluded with the if-condition (d < 4095).
protected void imageIR_MouseClick(object sender, System.Windows.Input.MouseEventArgs e)
{
// Get the x and y coordinates of the mouse pointer.
System.Windows.Point mousePoint = e.GetPosition(imageIR);
double xpos_IR = mousePoint.X;
double ypos_IR = mousePoint.Y;
int x = (int)xpos_IR;
int y = (int)ypos_IR;
lbCoord.Content = "x- & y- Koordinate [pixel]: " + x + " ; " + y;
int d = (ushort)pixelData[x + y * this.depthFrame.Width];
d = d >> 3;
int xpos_Content = (int)((x - 320) * 0.03501 / 2 * d/10);
int ypos_Content = (int)((240 - y) * 0.03501 / 2 * d/10);
xpos.Content = "x- Koordinate [mm]: " + xpos_Content;
ypos.Content = "y- Koordinate [mm]: " + ypos_Content;
zpos.Content = "z- Koordinate [mm]: " + (d);
// Calculate the average value of array element
int sum = 0;
int i;
i = Convert.ToInt32(gr_ordnung.Text);
i = int.Parse(gr_ordnung.Text);
int m;
int n;
int d_mw = 0;
int count = 0;
for (m = x - i; m <= x + i; m++)
{
for (n = y - i; n <= y + i; n++)
{
int d_array = (ushort)pixelData[m + n * this.depthFrame.Width];
d_array = d_array >> 3;
// With condition that if one of those values is more than 4095:
if (d_array <= 4095)
{
sum += d_array;
count++;
d_mw = sum / count;
}
tiefen_mw.Content = "Tiefen-MW [mm]: " + d_mw;
}
}
}
So, the 'if' condition means if I have d_array (in my case 100 Pixels) from m = x-i to m = x+i and n = y-i to n = y+i which is less than 4095 then just do the 'normal' calculation where the average is the sum of all values divided by the number of total elements.
Now the 'else' condition means: if I have d_array value which is more than 4095, then it should be declared as 0 and it doesn't count in the average. Did I write the Syntax correctly?
You could use LinQ to do this quite easily:
using System.Linq;
...
int[] values = new int[10];
// Fill array
...
int[] usefulValues = values.Where(i => i <= 4095).ToArray();
int numberOfUselessValues = values.Length - usefulValues.Length;
UPDATE >>>
Try this instead:
int count_useful = 0; // <<< Important to initialise this here
for (m = x - i; m <= x + i; m++)
{
for (n = y - i; n <= y + i; n++)
{
int d_array = (ushort)pixelData[m + n * this.depthFrame.Width];
d_array = d_array >> 3;
if (d_array <= 4095)
{
sum += d_array;
count_useful++;
}
}
}
d_mw = sum / count_useful; // <<< Perform these sums outside of the loop
tiefen_mw.Content = "Tiefen-MW [mm]: " + d_mw;
Just check before you do anything:
int d_array = (ushort)pixelData[m + n * this.depthFrame.Width];
d_array = d_array >> 3;
if (d_array > 4095) continue; // <-- this
Without knowing more.. its hard to give you a nicer answer.
i want to print the expression Xmin and Ymin as is without calculating the final value .
i,e with the values of I and J as 1,2,3,4,5
example
when I=1
Xmin= Xmin ((1 - 1)*10 + (1 - 1)*1)
is there a way to do it .. I tried the following code, but no luck:
int a, g;
a = 10;
g = 1;
for (int J=1; J<=5; J++)
{
for (int I = 1; I <= 5; I++)
{
string Xmin = Convert.ToString((I - 1)*a + (I - 1)*g);
string Ymin = Convert.ToString((J - 1) * a);
Debug.WriteLine("X=" + Xmin + "Y=" + Ymin);
}
}
You must use String.Format:
string Xmin = String.Format("({0} - 1)*{1} + ({0} - 1)*{2}", I, a, g);
Also, in .NET 3.5 you can use expression trees, but I daresay that would be a much more complicated solution than just using String.Format.
You need to put the expression in a string in order to do that, perhaps using String.Format
string Xmin = String.Format("Xmin=({0} - 1)*{1} + ({0} - 1)*{2}", I, a, g);
string Ymin = String.Format("Ymin=({0} - 1) * {1}", J, a);
Debug.WriteLine("X=" + Xmin + "Y=" + Ymin);