programasde c#
TRANSCRIPT
Pues eso, como e empezado hace pokito con C# he heho los típicos ejercicios básicos y los
keria compartir con vosotros, y si kereis pues animaros y poner alguno vuestro
Mini-Calculadora en modo consola:Códigousing System; namespace Calculadora{
class Program{
public static void Main(string[] args){
float primero; // El primer númerofloat segundo; // El segundo númerostring operacion; // La operación a
realizar
Console.Title = "Mini-Calculadora"; // Damos formato a la consola
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Blue;
Console.Clear();
Console.SetCursorPosition (3,2); // Pedimos el primer número
Console.WriteLine ("Introduzca el primer número");
Console.SetCursorPosition (60,2);primero = float.Parse(Console.ReadLine());
Console.SetCursorPosition (3,3); // Pedimos
la operaciónConsole.WriteLine ("Introduzca la operación
a realizar (+,-,*,/)");Console.SetCursorPosition (59,3);operacion = Console.ReadLine();
Console.SetCursorPosition (3,4); // Pedimos
el segundo númeroConsole.WriteLine ("Introduzca el segundo
número");Console.SetCursorPosition (60,4);segundo = float.Parse(Console.ReadLine());
Console.SetCursorPosition (57,5); // Mostramos la solucion...
Console.WriteLine ("__________");
Console.SetCursorPosition (3,6);Console.WriteLine ("El resultado es");Console.SetCursorPosition (60,6);
Console.WriteLine
(calcular(primero,segundo,operacion));Console.ReadKey ();
}
private static string calcular (float primero , float
segundo, string operacion){
float temp;switch (operacion) // Estructura con switch{
case "+":temp = primero + segundo;return temp.ToString ();
case "-":temp = primero - segundo;return temp.ToString ();
case "*":temp = primero * segundo;return temp.ToString ();
case "/":temp = primero / segundo;return temp.ToString ();
}return "-1";
}}
}
Mini-Calculadora en modo gráfico: (los nombres de los controles son faciles de deducir
viendo el code ) Códigousing System;using System.Collections.Generic;using System.Drawing;using System.Windows.Forms;using System.Text; namespace Calculadora{
/// <summary>/// Description of MainForm./// </summary>public partial class MainForm : Form{
int oper ; // 1 -> + | 2 -> - | 3 -> * | 4 -> /float primero;
public MainForm(){
InitializeComponent();}
void Numero7Click(object sender, EventArgs e){
txtnum.Text = txtnum.Text + 7;}
void Numero8Click(object sender, EventArgs e){
txtnum.Text = txtnum.Text + 8;}
void Numero9Click(object sender, EventArgs e){
txtnum.Text = txtnum.Text + 9;}
void Numero4Click(object sender, EventArgs e){
txtnum.Text = txtnum.Text + 4;}
void Numero5Click(object sender, EventArgs e){
txtnum.Text = txtnum.Text + 5;}
void Numero6Click(object sender, EventArgs e){
txtnum.Text = txtnum.Text + 6;}
void Numero1Click(object sender, EventArgs e){
txtnum.Text = txtnum.Text + 1;}
void Numero2Click(object sender, EventArgs e){
txtnum.Text = txtnum.Text + 2;}
void Numero3Click(object sender, EventArgs e){
txtnum.Text = txtnum.Text + 3;}
void Numero0Click(object sender, EventArgs e){
txtnum.Text = txtnum.Text + 0;}
void CClick(object sender, EventArgs e){
txtnum.Text = "";}
void DivClick(object sender, EventArgs e){
oper = 4;primero = float.Parse (txtnum.Text);txtnum.Text = "";
}
void MulClick(object sender, EventArgs e){
oper = 3;primero = float.Parse (txtnum.Text);txtnum.Text = "";
}
void ResClick(object sender, EventArgs e){
oper = 2;primero = float.Parse (txtnum.Text);txtnum.Text = "";
}
void SumClick(object sender, EventArgs e){
oper = 1;primero = float.Parse (txtnum.Text);txtnum.Text = "";
}
void SolClick(object sender, EventArgs e){
float segundo = int.Parse (txtnum.Text);float resultado;
switch (oper) {
case 1:resultado = primero + segundo;txtnum.Text =
resultado.ToString();break;
case 2:resultado = primero - segundo;txtnum.Text = resultado.ToString();break;
case 3:resultado = primero * segundo;txtnum.Text = resultado.ToString();break;
case 4:resultado = primero / segundo;txtnum.Text = resultado.ToString();break;
}}
}}
Un ejemplo muy simple para resolver ecuaciones de seegundo grado (añadir 3 text box y un boton):Códigousing System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms; namespace Ecuaciones{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void resolver_Click(object sender, EventArgs e) { ecuacion miEcuacion = new ecuacion (double.Parse(a.Text), double.Parse(b.Text), double.Parse(c.Text)); } }}
Exporador de carpetas: (añadir un text box "txtRuta" dos listas "lbcar" y "lbar" y un boton con nombre por defecto)Códigousing System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.IO; namespace ExploradorCarpetas{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } // El form load private void Form1_Load(object sender, EventArgs e) { // Iniciamos el txtRuta
txtRuta.Text = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory()); // Listamos las carpetas carpetas(txtRuta.Text); // Listamos los archivos archivos(txtRuta.Text); } // El botón para explorar rutas private void button1_Click(object sender, EventArgs e) { // Listamos las carpetas carpetas(txtRuta.Text); // Listamos los archivos archivos(txtRuta.Text); } // Al hacer doble click sobre una ruta la colocamos en txtRuta private void lbcar_DoubleClick(object sender, EventArgs e) { txtRuta.Text = lbcar.SelectedItem.ToString(); // Listamos las carpetas carpetas(txtRuta.Text); // Listamos los archivos archivos(txtRuta.Text); } // Metodo que coloca las carpetas de la ruta indicada en el list // box correspondiente private void carpetas(string ruta) { lbcar.Items.Clear(); string[] carpeta = Directory.GetDirectories(ruta); foreach(string car in carpeta) lbcar.Items.Add (car); } // Metodo que coloca los archivos de la ruta indicada en el list // box correspondiente private void archivos(string ruta) { lbar.Items.Clear(); string[] archivo = Directory.GetFiles(ruta); foreach (string ar in archivo) lbar.Items.Add(ar); } }}
Operaciones simples con matrices:Códigousing System; namespace Matrices{
class Program{
public static void Main(string[] args){
float [,] mat1; // Las matricesfloat [,] mat2;
int f1, c1; // El número de filas y columnas de
las matricesint f2, c2;
//Llamamos al menu y recojemos la opción
seleccionadabyte opcion;do {
opcion = menu();} while (opcion >= 5);
switch (opcion){
case 1: // SUMA
// Leemos el número de filas y columnas de las matrices 1 y 2
Console.WriteLine ("Introduzca el número de filas de las matrices 1 y 2");
f1 = int.Parse (Console.ReadLine());
Console.WriteLine ("Introduzca el número de columnas de las matrices 1 y 2");
c1 = int.Parse (Console.ReadLine());
// Pedimos los datos de filas y columnas
Console.WriteLine ("Introduzca los datos de la matriz 1 enumerandolos por filas:");
mat1 = leer(f1,c1);Console.WriteLine ("Introduzca los
datos de la matriz 2 enumerandolos por filas:");mat2 = leer(f1,c1);
//Mostramos la suma de ambas
matricessuma(mat1,mat2);break;
case 2: // RESTA
// Leemos el número de filas y
columnas de las matrices 1 y 2Console.WriteLine ("Introduzca el
número de filas de las matrices 1 y 2");f1 = int.Parse
(Console.ReadLine());Console.WriteLine ("Introduzca el
número de columnas de las matrices 1 y 2");c1 = int.Parse
(Console.ReadLine());
// Pedimos los datos de filas y columnas
Console.WriteLine ("Introduzca los datos de la matriz 1 enumerandolos por filas:");
mat1 = leer(f1,c1);Console.WriteLine ("Introduzca los
datos de la matriz 2 enumerandolos por filas:");mat2 = leer(f1,c1);
// Mostramos la resta de ambas
matricesresta (mat1, mat2);break;
case 3: // PRODUCTO POR UN ESCALAR
// Leemos el número de filas y
columnas de la matriz 1Console.WriteLine ("Introduzca el
número de filas de la matriz 1");f1 = int.Parse
(Console.ReadLine());Console.WriteLine ("Introduzca el
número de columnas de la matriz 1");c1 = int.Parse
(Console.ReadLine());
float escalar;Console.WriteLine ("Introduzca el
escalar por el que quiere multiplicar la matriz");escalar =
float.Parse(Console.ReadLine());
// Pedimos los datos de filas y columnas
Console.WriteLine ("Introduzca los datos de la matriz 1 enumerandolos por filas:");
mat1 = leer(f1,c1);
// Mostramos la soluciónprodEscalar (mat1,escalar);
break;
}
Console.ReadKey();}
// Función que muestra el menu de selección de operacionespublic static byte menu(){
try {byte opcion;Console.SetCursorPosition(10,1);Console.WriteLine("Menú:");Console.SetCursorPosition(0,3);Console.WriteLine("Elija la operación que
quiere hacer:");Console.WriteLine("1 - Suma de matrices");Console.WriteLine("2 - Resta de matrices");Console.WriteLine("3 - Producto por un
escalar");
opcion = byte.Parse (Console.ReadLine());
if (opcion >=1 && opcion <=3) {Console.Clear();return opcion;
}else {
Console.Clear();return 5;
}} catch { //En caso de error
Console.Clear();return 5;
}}
// Función que lee los datos de las matricespublic static float [,] leer(int filas, int columnas){
float [,] ret = new float [filas, columnas];for (int fila = 0; fila < filas; fila++){
for (int columna = 0; columna < columnas; columna++)
{ret[fila,columna] = float.Parse
(Console.ReadLine());}
}return ret;
}
// La función sumapublic static void suma (float [,] mat1, float [,] mat2){
Console.WriteLine ("La suma de sus dos matrices es (enumeradas por filas)");
for (int fila = 0; fila <= mat2.GetUpperBound(0); fila++)
{for (int columna = 0; columna <=
mat2.GetUpperBound(1); columna++){
float suma;suma = mat1[fila,columna] +
mat2[fila,columna];Console.WriteLine
(suma.ToString());}Console.WriteLine("");
}}
// La función restapublic static void resta (float [,] mat1, float [,] mat2){
Console.WriteLine ("La resta de sus dos matrices es (enumeradas por filas)");
for (int fila = 0; fila <= mat2.GetUpperBound(0); fila++)
{for (int columna = 0; columna <=
mat2.GetUpperBound(1); columna++){
float resta;resta = mat1[fila,columna] -
mat2[fila,columna];Console.WriteLine
(resta.ToString());}Console.WriteLine("");
}}
// Producto por un escalarpublic static void prodEscalar (float [,] mat1, float
escalar){
Console.WriteLine ("La multiplicación del escalar por su matriz es (enumerada por filas)");
for (int fila = 0; fila <= mat1.GetUpperBound(0); fila++)
{for (int columna = 0; columna <=
mat1.GetUpperBound(1); columna++){
float esc;esc = mat1[fila,columna] * escalar;Console.WriteLine (esc.ToString());
}Console.WriteLine("");
}}
}}
Windows-pong, con dos botones y un radio buton simulo en clasico pong, muy cutre pero entretenido xDDD
Códigousing System;using System.Collections.Generic;using System.Drawing;using System.Windows.Forms; namespace MiniJuegoPelota{
/// <summary>/// Description of MainForm./// </summary>public partial class MainForm : Form{
// 1 -> Derecha -1 -> Izquierda// 1 -> Abajo -1 -> Arribaprivate int dx = -1, dy = 1;
// Variables q contiene la ultima tecla pulsada por cierta
pala// para q el rebote se efectue en una o otra direcion// 'u' (up) -> arriba 'd' (down) -> abajoprivate char d1, d2;
public MainForm(){
InitializeComponent();}
void Timer1Tick(object sender, EventArgs e){
// Movemos la "pelota"pelota.Left += dx;pelota.Top += dy;
// Para el movimiento de la pelota
//dx = pelota.Location.X >=
this.ClientSize.Width ? -1 : dx;//dx = pelota.Location.X == 0 ? 1 : dx;
if (pelota.Location.X + 18 >=
this.ClientSize.Width){
timer1.Enabled = false;MessageBox.Show("Gana el jugador 1",
"Felicidades");}if (pelota.Location.X == 0){
timer1.Enabled = false;MessageBox.Show("Gana el jugador 2",
"Felicidades");}
// Si choca contra la parte inferior o el menúdy = pelota.Location.Y + 50 >=
this.ClientSize.Width ? -1 : dy;dy = pelota.Location.Y == 25 ? 1 : dy;
// Si choca contra la pala1if (pelota.Left == pala1.Left + pala1.Width){
if (pelota.Top > pala1.Top && pelota.Top < pala1.Top + pala1.Height)
{dx = 1; // Hacemos que valla hacia
la derecha// y en funcion de la ultima tecla
pulsada hacia arriba o abajody = d1 == 'u' ? -1 : 1;
}}
// Si choca contra la pala2if (pelota.Left == pala2.Left - pala2.Width){
if (pelota.Top > pala2.Top && pelota.Top < pala2.Top + pala2.Height)
{dx = -1; // Hacemos que valla hacia
la izq// y en funcion de la ultima tecla
pulsada hacia arriba o abajody = d2 == 'u' ? -1 : 1;
}}
}
//Para mover la pala 1 A = arriba, Z = abajo//Para mover la pala 2 K = arriba, M = abajovoid MainFormKeyPress(object sender, KeyPressEventArgs e){
switch (Char.ToUpper(e.KeyChar)){case 'A': //La pala1
pala1.Top -= 10;if (pala1.Top < 25) pala1.Top = 25;d1 = 'u';break;
case 'Z':pala1.Top += 10;if (pala1.Top + pala1.Height >=
this.ClientSize.Height) pala1.Top = this.ClientSize.Height - pala1.Height;
d1 = 'd';
break;
case 'K': //La pala2pala2.Top -= 10;if (pala2.Top < 25) pala2.Top = 25;d2 = 'u';break;
case 'M':
pala2.Top += 10;if (pala2.Top + pala2.Height >=
this.ClientSize.Height) pala2.Top = this.ClientSize.Height - pala2.Height;
d2 = 'd';break;
}}
// Las opciones del menúvoid NuevoToolStripMenuItemClick(object sender, EventArgs
e){
timer1.Enabled = true;pelota.Left = 154;pelota.Top = 134;
}
void ContrrolesToolStripMenuItemClick(object sender, EventArgs e)
{MessageBox.Show ("Pulsar las teclas A y K para
subir y las teclas Z y M para bajar las respectivas paletas de los jugadores 1 y 2", "Controles");
}
void SalirToolStripMenuItemClick(object sender, EventArgs e)
{Application.Exit();
}}
}
http://foro.elhacker.net/net/ejercicios_basicos_c-t185614.0.html#ixzz154rOgpNM
Estoy empezando con c#, añado dos aunke mas simples.
1-Es como el sorteo de la once, te pregunta k numero tenemos i te dice las coincidencias con el numero premiado y el premio.
Código:using System;using System.Collections.Generic;using System.Text;
namespace Exercici22_UD2{ class Program { static void Main(string[] args) { Random r = new Random(); int num, cupo,r1,r2,r3,r4,n1,n2,n3,n4,a1,a2,a3,a4,c1,c2,c3,c4; cupo = r.Next(100000); Console.WriteLine("Que numero tenemos (5 digitos)"); num = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("el numero premiado es " + cupo); n1 = cupo / 10; r1 = cupo % 10; n2 = n1 / 10; r2 = n1 % 10; n3 = n2 / 10; r3 = n2 % 10; n4 = n2 / 10; r4 = n3 / 10;
a1 = num / 10; c1 = num % 10; a2 = a1 / 10; c2 = a1 % 10; a3 = a2 / 10; c3 = a2 / 10; a4 = a3 / 10; c4 = a3 % 10; if (num==cupo) Console.WriteLine("Coincidencia de los 5 digitos, has ganado 33.000 euros"); else if (r1==c1 && r2==c2 && r3==c3 && r4==c4) Console.WriteLine("Coincidencia de los 4 ultimos digitos, has ganado 150 euros"); else if (r1==c1 && r2==c2 && r3==c3) Console.WriteLine("Coincidencia de los 3 ultimos digitos, has guanyat 15 euros"); else if (r1==c1 && r2==c2) Console.WriteLine("Coincidencia de los 2 ultimos digitos, has ganado 5 euros"); else if (r1==c1) Console.WriteLine("Coincidencia en el ultimo digito, has ganado 1,5 euros"); else Console.WriteLine("Ninguna coincidencia, no has ganado nada");
} }}
2-Es un reloj digital con alarma.
Código:using System;using System.Collections.Generic;using System.Text;
namespace rellotgeDigitalAmbAlarma{ class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Red; Console.BackgroundColor = ConsoleColor.Yellow; Console.Clear(); int h, m, s, x; int alarmaH, alarmaM, alarmaS; String alarma; Console.WriteLine("Introdueix les hores"); h = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Introdueix els minuts"); m = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Introdueix els segons"); s = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Vols possar alarma, si o no"); alarma = Convert.ToString(Console.ReadLine());
if (alarma == "si") { Console.Clear(); Console.WriteLine("Introdueix les hores de l'alarma"); alarmaH = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Introdueix els minuts de l'alarma"); alarmaM = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Introdueix els segons de l'alarma"); alarmaS = Convert.ToInt32(Console.ReadLine());
} else { alarmaH = -1; alarmaM = -1; alarmaS = -1; }
while (true) { Console.Clear();
Console.WriteLine("Son les {0}:{1}:{2}", h, m, s); x = Environment.TickCount; while (Environment.TickCount <= x + 1000) ; s = s + 1; if (alarmaH == h && alarmaM == m && alarmaS == s) { Console.Beep(); Console.Beep(); Console.Beep();
}
if (s == 60) { s = 0; m = m + 1; if (m == 60) { m = 0; h = h + 1; if (h == 24) { h = 0;
} } }
}
}
}}
http://foro.elhacker.net/net/ejercicios_basicos_c-t185614.0.html#ixzz154s6RFLB
Mensajes: 393
Re: Ejercicios básicos C#« Respuesta #7 en: 23 Noviembre 2007, 22:40 »
otro programita en C# , un programita que te saca la ipotenusa de dos valores esta en modo visual
son 2 textboxun boton
Código:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;
namespace Hipotenusa{ public partial class Form1 : Form { double t; public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { double a = 0; double b = 0; double m = 0; a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); t = Math.Pow(a,2) +Math.Pow(b,2) ; m = Math.Sqrt(t); MessageBox.Show("La Hipotenusa es " + m);
} }}
http://foro.elhacker.net/net/ejercicios_basicos_c-t185614.0.html#ixzz154sKqaKg
aki dejo otro programita que lo acabo de terminar::Este programa ase las conversiones de kelvin, celsius, Fahrenheit, de todos los tipos objetos necesarios "indispensables" (Por si le quieres poner etiquetas y adornar)Dos textboxseis radioButtondos botonesun listbox
Dejo una imagen
Aclaro que se puede acer un poko mas corto con clases
Código:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;
namespace Centigrados{ public partial class Form1 : Form { int b,a; double t; int cad; string tot; public Form1() { InitializeComponent(); } private void radioButton1_CheckedChanged(object sender, EventArgs e) { try { a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); cad = listBox1.Items.Add("Celsius kelvin"); if (a < b) { } else {
MessageBox.Show("Error en los datos","Tecnologico de la Paz"); } while (a <= b) { for (int x = a; x <= a; x++) { t = a + 273.15; tot = x.ToString() + " " + t.ToString(); } listBox1.Items.Add(tot); a++; } } catch (FormatException ms) { MessageBox.Show("Error en los datos de entrada", "Tecnologico de la Paz"); textBox1.Text = ""; textBox2.Text = ""; radioButton1.Checked = false; } } private void button2_Click(object sender, EventArgs e) { radioButton1.Checked = false; radioButton2.Checked = false; radioButton3.Checked = false; radioButton4.Checked = false; radioButton5.Checked = false; radioButton6.Checked = false; listBox1.Items.Clear(); textBox1.Text = ""; textBox2.Text = ""; textBox1.Focus(); } private void Form1_Load(object sender, EventArgs e) { MessageBox.Show("Bienvenidos al convertidor de temperaturas", "Tecnologico de la Paz"); } private void Form1_Load_1(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { this.Close(); } private void radioButton2_CheckedChanged(object sender, EventArgs e) { listBox1.Items.Clear(); try { /*if (a < b) {
} else { MessageBox.Show("Error en los datos", "Tecnologico de la Paz"); textBox1.Focus(); listBox1.Items.Clear(); }*/ a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); cad = listBox1.Items.Add("Kelvin Celsius"); while (a <= b) { for (int x = a; x <= a; x++) { t = a - 273.15; tot = x.ToString() + " " + t.ToString(); } listBox1.Items.Add(tot); a++; } } catch (FormatException ms) { MessageBox.Show("Error en los datos de entrada", "Tecnologico de la Paz"); textBox1.Text = ""; textBox2.Text = ""; radioButton2.Checked = false; } } private void radioButton3_CheckedChanged(object sender, EventArgs e) { listBox1.Items.Clear(); try { /*if (a < b) { } else { MessageBox.Show("Error en los datos", "Tecnologico de la Paz"); textBox1.Focus(); textBox1.Text = ""; textBox2.Text = ""; listBox1.Items.Clear(); }*/ a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); cad = listBox1.Items.Add("Fahrenhet Celsius"); while (a <= b) { for (int x = a; x <= a; x++) {
t = (a - 32)/1.8; tot = x.ToString() + " " + t.ToString(); } listBox1.Items.Add(tot); a++; } } catch (FormatException ms) { MessageBox.Show("Error en los datos de entrada", "Tecnologico de la Paz"); textBox1.Text = ""; textBox2.Text = ""; radioButton3.Checked = false; } } private void radioButton4_CheckedChanged(object sender, EventArgs e) { listBox1.Items.Clear(); try { /*if (a < b) { } else { MessageBox.Show("Error en los datos", "Tecnologico de la Paz"); textBox1.Focus(); textBox1.Text = ""; textBox2.Text = ""; listBox1.Items.Clear(); }*/ a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); cad = listBox1.Items.Add("Celsius Fahrenhet"); while (a <= b) { for (int x = a; x <= a; x++) { t = (a *1.8) +32; tot = x.ToString() + " " + t.ToString(); } listBox1.Items.Add(tot); a++; } } catch (FormatException ms) { MessageBox.Show("Error en los datos de entrada", "Tecnologico de la Paz"); textBox1.Text = ""; textBox2.Text = ""; radioButton4.Checked = false;
} } private void radioButton5_CheckedChanged(object sender, EventArgs e) { listBox1.Items.Clear(); try { /*if (a < b) { } else { MessageBox.Show("Error en los datos", "Tecnologico de la Paz"); textBox1.Focus(); textBox1.Text = ""; textBox2.Text = ""; listBox1.Items.Clear(); }*/ a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); cad = listBox1.Items.Add("Kelvin Fahrenhet"); while (a <= b) { for (int x = a; x <= a; x++) { t = (a * 1.8) -459.67 ; tot = x.ToString() + " " + t.ToString(); } listBox1.Items.Add(tot); a++; } } catch (FormatException ms) { MessageBox.Show("Error en los datos de entrada", "Tecnologico de la Paz"); textBox1.Text = ""; textBox2.Text = ""; radioButton5.Checked = false; } } private void radioButton6_CheckedChanged(object sender, EventArgs e) { listBox1.Items.Clear(); try { /*if (a < b) { } else { MessageBox.Show("Error en los datos", "Tecnologico de la Paz");
textBox1.Focus(); textBox1.Text = ""; textBox2.Text = ""; listBox1.Items.Clear(); }*/ a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); cad = listBox1.Items.Add("Fahrenhet Kelvin"); while (a <= b) { for (int x = a; x <= a; x++) { t = (a + 459.67) / 1.8; tot = x.ToString() + " " + t.ToString(); } listBox1.Items.Add(tot); a++; } } catch (FormatException ms) { MessageBox.Show("Error en los datos de entrada", "Tecnologico de la Paz"); textBox1.Text = ""; textBox2.Text = ""; radioButton6.Checked = false; } }
private void textBox2_Enter(object sender, EventArgs e) { } }}
http://foro.elhacker.net/net/ejercicios_basicos_c-t185614.0.html#ixzz154t9gJNz
Mensajes: 393
Re: Ejercicios básicos C#« Respuesta #4 en: 22 Noviembre 2007, 06:56 »
Dejo tamvien mi granito de arena, Otra calculadora
Dos botones Dos TextboxUn comboBox (Para poner que tipo de operacion)
Este tiene las opciones de + , - , * , / , ^ , %
Código:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;
namespace WindowsApplication1{ public partial class Form1 : Form { int a; int b; string res; double result;
public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { MessageBox.Show("Bienvenidos ala calculadora Recuerde Poder los valores correctos", "Tecnologico de la paz"); }
private void button1_Click(object sender, EventArgs e) {
try { a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); res = comboBox1.SelectedItem.ToString();
if (res == "+") { result = a + b; MessageBox.Show("La suma de la Cantidad es " + result.ToString());
} if (res == "-") { result = a - b; MessageBox.Show("La Resta de la Cantidad es " + result.ToString());
} if (res == "*") { result = a * b; MessageBox.Show("La Multiplicacion de las Cantidades es " + result.ToString());
} if (res == "/") { result = a / b; MessageBox.Show("La Division de las Cantidades es " + result.ToString());
} if (res == "^") { result = Math.Pow(a, b); MessageBox.Show("El resultado es " + result.ToString());
} if (res == "%") { result = (a % b); MessageBox.Show("el porcentaje es " + result.ToString()); } textBox1.Text = ""; textBox2.Text = ""; textBox1.Focus(); comboBox1.Text = ""; }
catch (DivideByZeroException lms) { MessageBox.Show("Error Escriba los datos correctamente", "Mensaje de Error"); textBox1.Text = ""; textBox2.Text = ""; textBox1.Focus(); comboBox1.Text = ""; }
catch (FormatException ms) { MessageBox.Show("Error Escriba los datos correctamente", "Mensaje de Error"); textBox1.Text = ""; textBox2.Text = ""; textBox1.Focus();
} } private void button2_Click(object sender, EventArgs e) { this.Close(); } }}
http://foro.elhacker.net/net/ejercicios_basicos_c-t185614.0.html#ixzz154sClmAH