Hola amigos soy nuevo en C#, necesito ayuda para la solución de un programa el cual pide lo siguiente:
1.Solicite al usuario la captura de dos valores numéricos.
2.Pregunte el tipo de operación que se desea realizar: suma, resta, multiplicación, división (solamente se puede seleccionar una operación).
3.Devuelva en pantalla el resultado de la operación elegida.
4.Pregunte si se desea realizar una nueva operación y en caso de contestar que sí, el programa debe repetir desde el paso 1 (pedir los dos números) al paso 4, hasta que el usuario responda que ya no desea continuar.
Me trave en el paso 2 y no se como entrar en el ciclo para volver a preguntar:
Console.WriteLine("Ingresar el primer numero");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Ingresar el segundo numero");
int num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Elija la Operacion aritmetica");
Console.WriteLine("Oprima s para SUMAR");
Console.WriteLine("Oprima r para RESTAR");
Console.WriteLine("Oprima m para MULTIPLICAR");
Console.WriteLine("Oprima d para DIVIDIR");
int s = 1;
s = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(Convert.ToString(s));
while (s <= 1);
{
s = num1 + num2;
Console.WriteLine(Convert.ToString(s));
Espero que alguien pueda ayudarme saludos cordiales. :rolleyes:
Supongo que seria algo asi toma en cuenta que no valido los datos de entrada:
static void Main(string[] args)
{
EjecutarPrograma();
Console.WriteLine("Precione una tecla para continuar...");
Console.ReadKey();
}
public static void EjecutarPrograma()
{
bool salir = false;
int num1 = 0;
int num2 = 0;
int respuesta=0;
string operacion = string.Empty;
while (!salir)
{
Console.WriteLine("Ingresar el primer numero");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Ingresar el segundo numero");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Elija la Operacion aritmetica");
Console.WriteLine("Oprima s para SUMAR");
Console.WriteLine("Oprima r para RESTAR");
Console.WriteLine("Oprima m para MULTIPLICAR");
Console.WriteLine("Oprima d para DIVIDIR");
operacion = Console.ReadLine();
switch (operacion)
{
case "s":
respuesta = num1 + num2;
break;
case "r":
respuesta = num1 - num2;
break;
//y asi va agrenando operadores
default:
respuesta = 0;
break;
}
Console.WriteLine(String.Format("La prespuesta es: {0}", respuesta));
//aqui preguntas si quieres continuar
Console.WriteLine("Precione s para continuar");
if (Console.ReadLine() != "s")
salir = true;
}
}
Ok muchas gracias mi estimado, me has despejado varias dudas la verdad no tenia idea de la instruccion swicht y como usarla.
Espero no haberte quitado tu tiempo, esta claro que debo empalparme màs con respecto al tema, te agradezco nuevamente y saludos cordiales. ;-)
En el código de .::IT::. se está asumiendo que los valores sean enteros y que el resultado también lo sea, pero obviamente el resultado de la suma de dos Int32 podría dar un valor más alto (ej: Int64)
Aquí tienes mi versión, por si te sirve de algo:
Module Module1
#Region " Enumerations "
''' <summary>
''' Indicates an arithmetic operation.
''' </summary>
Public Enum ArithmeticOperation As Integer
''' <summary>
''' Any arithmetic operation.
''' </summary>
None = 0
''' <summary>
''' Sums the values.
''' </summary>
Sum = 1I
''' <summary>
''' Subtracts the values.
''' </summary>
Subtract = 2I
''' <summary>
''' Multiplies the values.
''' </summary>
Multiply = 3I
''' <summary>
''' Divides the values.
''' </summary>
Divide = 4I
End Enum
#End Region
#Region " Entry Point (Main)"
''' <summary>
''' Defines the entry point of the application.
''' </summary>
Public Sub Main()
DoArithmetics()
End Sub
#End Region
#Region " Public Methods "
Public Sub DoArithmetics()
Dim ExitString As String = String.Empty
Dim ExitDemand As Boolean = False
Dim Operation As ArithmeticOperation = ArithmeticOperation.None
Dim Value1 As Decimal = 0D
Dim Value2 As Decimal = 0D
Dim Result As Decimal = 0D
Do Until ExitDemand
SetValue(Value1, "Ingresar el primer numero: ")
SetValue(Value2, "Ingresar el segundo numero: ")
Console.WriteLine()
SetOperation(Operation, "Elegir una operacion aritmética: ")
SetResult(Operation, Value1, Value2, Result)
Console.WriteLine()
Console.WriteLine(String.Format("El resultado es: {0}", CStr(Result)))
Console.WriteLine()
SetExit(ExitDemand, "S"c, "N"c, "¿Quiere salir? [S/N]: ")
Console.Clear()
Loop ' ExitDemand
End Sub
''' <summary>
''' Asks for a value and waits for the user-input to set the value.
''' </summary>
''' <param name="Value">The ByRefered variable to set the input result.</param>
''' <param name="message">The output message.</param>
Public Sub SetValue(ByRef Value As Decimal,
Optional ByVal message As String = "Enter a value: ")
Dim Success As Boolean = False
Do Until Success
Console.Write(message)
Try
Value = Decimal.Parse(Console.ReadLine().Replace("."c, ","c))
Success = True
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.WriteLine()
End Try
Loop ' Success
End Sub
''' <summary>
''' Asks for an arithmetic operation and waits for the user-input to set the value.
''' </summary>
''' <param name="Operation">The ByRefered variable to set the input result.</param>
''' <param name="message">The output message.</param>
Public Sub SetOperation(ByRef Operation As ArithmeticOperation,
Optional ByVal message As String = "Choose an operation: ")
Dim Success As Boolean = False
For Each Value As ArithmeticOperation In [Enum].GetValues(GetType(ArithmeticOperation))
Console.Write(String.Format("{0}={1} | ", CStr(Value), Value.ToString))
Next Value
Console.WriteLine()
Do Until Success
Console.Write(message)
Try
Operation = [Enum].Parse(GetType(ArithmeticOperation), Console.ReadLine, True)
Success = True
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.WriteLine()
End Try
Loop ' Success
End Sub
''' <summary>
''' Performs an arithmetic operation on the given values.
''' </summary>
''' <param name="Operation">The arithmetic operation to perform.</param>
''' <param name="Value1">The first value.</param>
''' <param name="Value2">The second value.</param>
''' <param name="Result">The ByRefered variable to set the operation result value.</param>
Public Sub SetResult(ByVal Operation As ArithmeticOperation,
ByVal Value1 As Decimal,
ByVal Value2 As Decimal,
ByRef Result As Decimal)
Select Case Operation
Case ArithmeticOperation.Sum
Result = Sum(Value1, Value2)
Case ArithmeticOperation.Subtract
Result = Subtract(Value1, Value2)
Case ArithmeticOperation.Multiply
Result = Multiply(Value1, Value2)
Case ArithmeticOperation.Divide
Result = Divide(Value1, Value2)
Case ArithmeticOperation.None
' Do Nothing
End Select
End Sub
''' <summary>
''' Asks for a Boolean value and waits for the user-input to set the value.
''' </summary>
''' <param name="ExitBool">The ByRefered variable to set the input result.</param>
''' <param name="TrueChar">Indicates the character threated as 'True'.</param>
''' <param name="FalseChar">Indicates the character threated as 'False'.</param>
''' <param name="message">The output message.</param>
Public Sub SetExit(ByRef ExitBool As Boolean,
Optional ByVal TrueChar As Char = "Y"c,
Optional ByVal FalseChar As Char = "N"c,
Optional ByVal message As String = "¿Want to exit? [Y/N]: ")
Dim Success As Boolean = False
Dim Result As Char = Nothing
Console.Write(message)
Do Until Success
Result = Console.ReadKey().KeyChar
Select Case Char.ToLower(Result)
Case Char.ToLower(TrueChar)
ExitBool = True
Success = True
Case Char.ToLower(FalseChar)
ExitBool = False
Success = True
Case Else
Console.Beep()
If Not Char.IsLetterOrDigit(Result) Then
Console.CursorLeft = 0
SetExit(ExitBool, TrueChar, FalseChar, message)
Else
Console.CursorLeft = Console.CursorLeft - 1
Console.Write(" ")
Console.CursorLeft = Console.CursorLeft - 1
End If
End Select ' Char.ToLower(Result)
Loop ' Success
End Sub
#End Region
#Region " Private Functions "
''' <summary>
''' Performs a Sum operation on the specified values.
''' </summary>
Private Function Sum(ByVal Value1 As Decimal,
ByVal Value2 As Decimal) As Decimal
Return (Value1 + Value2)
End Function
''' <summary>
''' Performs a subtraction operation on the specified values.
''' </summary>
Private Function Subtract(ByVal Value1 As Decimal,
ByVal Value2 As Decimal) As Decimal
Return (Value1 - Value2)
End Function
''' <summary>
''' Performs a multiplier operation on the specified values.
''' </summary>
Private Function Multiply(ByVal Value1 As Decimal,
ByVal Value2 As Decimal) As Decimal
Return (Value1 * Value2)
End Function
''' <summary>
''' Performs a divider operation on the specified values.
''' </summary>
Private Function Divide(ByVal Value1 As Decimal,
ByVal Value2 As Decimal) As Decimal
Return (Value1 / Value2)
End Function
#End Region
End Module
Traducción instantanea a C#:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
static class Module1
{
#region " Enumerations "
/// <summary>
/// Indicates an arithmetic operation.
/// </summary>
public enum ArithmeticOperation : int
{
/// <summary>
/// Any arithmetic operation.
/// </summary>
None = 0,
/// <summary>
/// Sums the values.
/// </summary>
Sum = 1,
/// <summary>
/// Subtracts the values.
/// </summary>
Subtract = 2,
/// <summary>
/// Multiplies the values.
/// </summary>
Multiply = 3,
/// <summary>
/// Divides the values.
/// </summary>
Divide = 4
}
#endregion
#region " Entry Point (Main)"
/// <summary>
/// Defines the entry point of the application.
/// </summary>
public static void Main()
{
DoArithmetics();
}
#endregion
#region " Public Methods "
public static void DoArithmetics()
{
string ExitString = string.Empty;
bool ExitDemand = false;
ArithmeticOperation Operation = ArithmeticOperation.None;
decimal Value1 = 0m;
decimal Value2 = 0m;
decimal Result = 0m;
while (!(ExitDemand)) {
SetValue(ref Value1, "Ingresar el primer numero: ");
SetValue(ref Value2, "Ingresar el segundo numero: ");
Console.WriteLine();
SetOperation(ref Operation, "Elegir una operacion aritmética: ");
SetResult(Operation, Value1, Value2, ref Result);
Console.WriteLine();
Console.WriteLine(string.Format("El resultado es: {0}", Convert.ToString(Result)));
Console.WriteLine();
SetExit(ref ExitDemand, 'S', 'N', "¿Quiere salir? [S/N]: ");
Console.Clear();
}
// ExitDemand
}
/// <summary>
/// Asks for a value and waits for the user-input to set the value.
/// </summary>
/// <param name="Value">The ByRefered variable to set the input result.</param>
/// <param name="message">The output message.</param>
public static void SetValue(ref decimal Value, string message = "Enter a value: ")
{
bool Success = false;
while (!(Success)) {
Console.Write(message);
try {
Value = decimal.Parse(Console.ReadLine().Replace('.', ','));
Success = true;
} catch (Exception ex) {
Console.WriteLine(ex.Message);
Console.WriteLine();
}
}
// Success
}
/// <summary>
/// Asks for an arithmetic operation and waits for the user-input to set the value.
/// </summary>
/// <param name="Operation">The ByRefered variable to set the input result.</param>
/// <param name="message">The output message.</param>
public static void SetOperation(ref ArithmeticOperation Operation, string message = "Choose an operation: ")
{
bool Success = false;
foreach (ArithmeticOperation Value in Enum.GetValues(typeof(ArithmeticOperation))) {
Console.Write(string.Format("{0}={1} | ", Convert.ToString(Value), Value.ToString));
}
Console.WriteLine();
while (!(Success)) {
Console.Write(message);
try {
Operation = Enum.Parse(typeof(ArithmeticOperation), Console.ReadLine, true);
Success = true;
} catch (Exception ex) {
Console.WriteLine(ex.Message);
Console.WriteLine();
}
}
// Success
}
/// <summary>
/// Performs an arithmetic operation on the given values.
/// </summary>
/// <param name="Operation">The arithmetic operation to perform.</param>
/// <param name="Value1">The first value.</param>
/// <param name="Value2">The second value.</param>
/// <param name="Result">The ByRefered variable to set the operation result value.</param>
public static void SetResult(ArithmeticOperation Operation, decimal Value1, decimal Value2, ref decimal Result)
{
switch (Operation) {
case ArithmeticOperation.Sum:
Result = Sum(Value1, Value2);
break;
case ArithmeticOperation.Subtract:
Result = Subtract(Value1, Value2);
break;
case ArithmeticOperation.Multiply:
Result = Multiply(Value1, Value2);
break;
case ArithmeticOperation.Divide:
Result = Divide(Value1, Value2);
break;
case ArithmeticOperation.None:
break;
// Do Nothing
}
}
/// <summary>
/// Asks for a Boolean value and waits for the user-input to set the value.
/// </summary>
/// <param name="ExitBool">The ByRefered variable to set the input result.</param>
/// <param name="TrueChar">Indicates the character threated as 'True'.</param>
/// <param name="FalseChar">Indicates the character threated as 'False'.</param>
/// <param name="message">The output message.</param>
public static void SetExit(ref bool ExitBool, char TrueChar = 'Y', char FalseChar = 'N', string message = "¿Want to exit? [Y/N]: ")
{
bool Success = false;
char Result = null;
Console.Write(message);
while (!(Success)) {
Result = Console.ReadKey().KeyChar;
switch (char.ToLower(Result)) {
case char.ToLower(TrueChar):
ExitBool = true;
Success = true;
break;
case char.ToLower(FalseChar):
ExitBool = false;
Success = true;
break;
default:
Console.Beep();
if (!char.IsLetterOrDigit(Result)) {
Console.CursorLeft = 0;
SetExit(ref ExitBool, TrueChar, FalseChar, message);
} else {
Console.CursorLeft = Console.CursorLeft - 1;
Console.Write(" ");
Console.CursorLeft = Console.CursorLeft - 1;
}
break;
}
// Char.ToLower(Result)
}
// Success
}
#endregion
#region " Private Functions "
/// <summary>
/// Performs a Sum operation on the specified values.
/// </summary>
private static decimal Sum(decimal Value1, decimal Value2)
{
return (Value1 + Value2);
}
/// <summary>
/// Performs a subtraction operation on the specified values.
/// </summary>
private static decimal Subtract(decimal Value1, decimal Value2)
{
return (Value1 - Value2);
}
/// <summary>
/// Performs a multiplier operation on the specified values.
/// </summary>
private static decimal Multiply(decimal Value1, decimal Value2)
{
return (Value1 * Value2);
}
/// <summary>
/// Performs a divider operation on the specified values.
/// </summary>
private static decimal Divide(decimal Value1, decimal Value2)
{
return (Value1 / Value2);
}
#endregion
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================