elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: AIO elhacker.NET 2021 Compilación herramientas análisis y desinfección malware


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Programa en C#
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Programa en C#  (Leído 3,811 veces)
Castiel

Desconectado Desconectado

Mensajes: 23


Ver Perfil
Programa en C#
« en: 4 Agosto 2014, 00:50 am »

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:


En línea

.::IT::.

Desconectado Desconectado

Mensajes: 167



Ver Perfil
Re: Programa en C#
« Respuesta #1 en: 4 Agosto 2014, 01:25 am »

Supongo que seria algo asi toma en cuenta que no valido los datos de entrada:

Código:
        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;
            }

        }


En línea

Simplemente .::IT::.
Castiel

Desconectado Desconectado

Mensajes: 23


Ver Perfil
Re: Programa en C#
« Respuesta #2 en: 4 Agosto 2014, 01:58 am »

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 línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.818



Ver Perfil
Re: Programa en C#
« Respuesta #3 en: 4 Agosto 2014, 10:19 am »

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:

Código
  1. Module Module1
  2.  
  3. #Region " Enumerations "
  4.  
  5.    ''' <summary>
  6.    ''' Indicates an arithmetic operation.
  7.    ''' </summary>
  8.    Public Enum ArithmeticOperation As Integer
  9.  
  10.        ''' <summary>
  11.        ''' Any arithmetic operation.
  12.        ''' </summary>
  13.        None = 0
  14.  
  15.        ''' <summary>
  16.        ''' Sums the values.
  17.        ''' </summary>
  18.        Sum = 1I
  19.  
  20.        ''' <summary>
  21.        ''' Subtracts the values.
  22.        ''' </summary>
  23.        Subtract = 2I
  24.  
  25.        ''' <summary>
  26.        ''' Multiplies the values.
  27.        ''' </summary>
  28.        Multiply = 3I
  29.  
  30.        ''' <summary>
  31.        ''' Divides the values.
  32.        ''' </summary>
  33.        Divide = 4I
  34.  
  35.    End Enum
  36.  
  37. #End Region
  38.  
  39. #Region " Entry Point (Main)"
  40.  
  41.    ''' <summary>
  42.    ''' Defines the entry point of the application.
  43.    ''' </summary>
  44.    Public Sub Main()
  45.  
  46.        DoArithmetics()
  47.  
  48.    End Sub
  49.  
  50. #End Region
  51.  
  52. #Region " Public Methods "
  53.  
  54.    Public Sub DoArithmetics()
  55.  
  56.        Dim ExitString As String = String.Empty
  57.        Dim ExitDemand As Boolean = False
  58.        Dim Operation As ArithmeticOperation = ArithmeticOperation.None
  59.        Dim Value1 As Decimal = 0D
  60.        Dim Value2 As Decimal = 0D
  61.        Dim Result As Decimal = 0D
  62.  
  63.        Do Until ExitDemand
  64.  
  65.            SetValue(Value1, "Ingresar el  primer numero: ")
  66.            SetValue(Value2, "Ingresar el segundo numero: ")
  67.            Console.WriteLine()
  68.  
  69.            SetOperation(Operation, "Elegir una operacion aritmética: ")
  70.            SetResult(Operation, Value1, Value2, Result)
  71.            Console.WriteLine()
  72.  
  73.            Console.WriteLine(String.Format("El resultado es: {0}", CStr(Result)))
  74.            Console.WriteLine()
  75.  
  76.            SetExit(ExitDemand, "S"c, "N"c, "¿Quiere salir? [S/N]: ")
  77.            Console.Clear()
  78.  
  79.        Loop ' ExitDemand
  80.  
  81.    End Sub
  82.  
  83.    ''' <summary>
  84.    ''' Asks for a value and waits for the user-input to set the value.
  85.    ''' </summary>
  86.    ''' <param name="Value">The ByRefered variable to set the input result.</param>
  87.    ''' <param name="message">The output message.</param>
  88.    Public Sub SetValue(ByRef Value As Decimal,
  89.                        Optional ByVal message As String = "Enter a value: ")
  90.  
  91.        Dim Success As Boolean = False
  92.  
  93.        Do Until Success
  94.  
  95.            Console.Write(message)
  96.  
  97.            Try
  98.                Value = Decimal.Parse(Console.ReadLine().Replace("."c, ","c))
  99.                Success = True
  100.  
  101.            Catch ex As Exception
  102.                Console.WriteLine(ex.Message)
  103.                Console.WriteLine()
  104.  
  105.            End Try
  106.  
  107.        Loop ' Success
  108.  
  109.    End Sub
  110.  
  111.    ''' <summary>
  112.    ''' Asks for an arithmetic operation and waits for the user-input to set the value.
  113.    ''' </summary>
  114.    ''' <param name="Operation">The ByRefered variable to set the input result.</param>
  115.    ''' <param name="message">The output message.</param>
  116.    Public Sub SetOperation(ByRef Operation As ArithmeticOperation,
  117.                            Optional ByVal message As String = "Choose an operation: ")
  118.  
  119.        Dim Success As Boolean = False
  120.  
  121.        For Each Value As ArithmeticOperation In [Enum].GetValues(GetType(ArithmeticOperation))
  122.            Console.Write(String.Format("{0}={1} | ", CStr(Value), Value.ToString))
  123.        Next Value
  124.  
  125.        Console.WriteLine()
  126.  
  127.        Do Until Success
  128.  
  129.            Console.Write(message)
  130.  
  131.            Try
  132.                Operation = [Enum].Parse(GetType(ArithmeticOperation), Console.ReadLine, True)
  133.                Success = True
  134.  
  135.            Catch ex As Exception
  136.                Console.WriteLine(ex.Message)
  137.                Console.WriteLine()
  138.  
  139.            End Try
  140.  
  141.        Loop ' Success
  142.  
  143.    End Sub
  144.  
  145.    ''' <summary>
  146.    ''' Performs an arithmetic operation on the given values.
  147.    ''' </summary>
  148.    ''' <param name="Operation">The arithmetic operation to perform.</param>
  149.    ''' <param name="Value1">The first value.</param>
  150.    ''' <param name="Value2">The second value.</param>
  151.    ''' <param name="Result">The ByRefered variable to set the operation result value.</param>
  152.    Public Sub SetResult(ByVal Operation As ArithmeticOperation,
  153.                         ByVal Value1 As Decimal,
  154.                         ByVal Value2 As Decimal,
  155.                         ByRef Result As Decimal)
  156.  
  157.        Select Case Operation
  158.  
  159.            Case ArithmeticOperation.Sum
  160.                Result = Sum(Value1, Value2)
  161.  
  162.            Case ArithmeticOperation.Subtract
  163.                Result = Subtract(Value1, Value2)
  164.  
  165.            Case ArithmeticOperation.Multiply
  166.                Result = Multiply(Value1, Value2)
  167.  
  168.            Case ArithmeticOperation.Divide
  169.                Result = Divide(Value1, Value2)
  170.  
  171.            Case ArithmeticOperation.None
  172.                ' Do Nothing
  173.  
  174.        End Select
  175.  
  176.    End Sub
  177.  
  178.    ''' <summary>
  179.    ''' Asks for a Boolean value and waits for the user-input to set the value.
  180.    ''' </summary>
  181.    ''' <param name="ExitBool">The ByRefered variable to set the input result.</param>
  182.    ''' <param name="TrueChar">Indicates the character threated as 'True'.</param>
  183.    ''' <param name="FalseChar">Indicates the character threated as 'False'.</param>
  184.    ''' <param name="message">The output message.</param>
  185.    Public Sub SetExit(ByRef ExitBool As Boolean,
  186.                       Optional ByVal TrueChar As Char = "Y"c,
  187.                       Optional ByVal FalseChar As Char = "N"c,
  188.                       Optional ByVal message As String = "¿Want to exit? [Y/N]: ")
  189.  
  190.        Dim Success As Boolean = False
  191.        Dim Result As Char = Nothing
  192.  
  193.        Console.Write(message)
  194.  
  195.        Do Until Success
  196.  
  197.            Result = Console.ReadKey().KeyChar
  198.  
  199.            Select Case Char.ToLower(Result)
  200.  
  201.                Case Char.ToLower(TrueChar)
  202.                    ExitBool = True
  203.                    Success = True
  204.  
  205.                Case Char.ToLower(FalseChar)
  206.                    ExitBool = False
  207.                    Success = True
  208.  
  209.                Case Else
  210.                    Console.Beep()
  211.  
  212.                    If Not Char.IsLetterOrDigit(Result) Then
  213.                        Console.CursorLeft = 0
  214.                        SetExit(ExitBool, TrueChar, FalseChar, message)
  215.                    Else
  216.                        Console.CursorLeft = Console.CursorLeft - 1
  217.                        Console.Write(" ")
  218.                        Console.CursorLeft = Console.CursorLeft - 1
  219.                    End If
  220.  
  221.            End Select ' Char.ToLower(Result)
  222.  
  223.        Loop ' Success
  224.  
  225.    End Sub
  226.  
  227. #End Region
  228.  
  229. #Region " Private Functions "
  230.  
  231.    ''' <summary>
  232.    ''' Performs a Sum operation on the specified values.
  233.    ''' </summary>
  234.    Private Function Sum(ByVal Value1 As Decimal,
  235.                         ByVal Value2 As Decimal) As Decimal
  236.  
  237.        Return (Value1 + Value2)
  238.  
  239.    End Function
  240.  
  241.    ''' <summary>
  242.    ''' Performs a subtraction operation on the specified values.
  243.    ''' </summary>
  244.    Private Function Subtract(ByVal Value1 As Decimal,
  245.                              ByVal Value2 As Decimal) As Decimal
  246.  
  247.        Return (Value1 - Value2)
  248.  
  249.    End Function
  250.  
  251.    ''' <summary>
  252.    ''' Performs a multiplier operation on the specified values.
  253.    ''' </summary>
  254.    Private Function Multiply(ByVal Value1 As Decimal,
  255.                              ByVal Value2 As Decimal) As Decimal
  256.  
  257.        Return (Value1 * Value2)
  258.  
  259.    End Function
  260.  
  261.    ''' <summary>
  262.    ''' Performs a divider operation on the specified values.
  263.    ''' </summary>
  264.    Private Function Divide(ByVal Value1 As Decimal,
  265.                            ByVal Value2 As Decimal) As Decimal
  266.  
  267.        Return (Value1 / Value2)
  268.  
  269.    End Function
  270.  
  271. #End Region
  272.  
  273. End Module
  274.  


Traducción instantanea a C#:

Código
  1. using Microsoft.VisualBasic;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7. static class Module1
  8. {
  9.  
  10. #region " Enumerations "
  11.  
  12. /// <summary>
  13. /// Indicates an arithmetic operation.
  14. /// </summary>
  15. public enum ArithmeticOperation : int
  16. {
  17.  
  18. /// <summary>
  19. /// Any arithmetic operation.
  20. /// </summary>
  21. None = 0,
  22.  
  23. /// <summary>
  24. /// Sums the values.
  25. /// </summary>
  26. Sum = 1,
  27.  
  28. /// <summary>
  29. /// Subtracts the values.
  30. /// </summary>
  31. Subtract = 2,
  32.  
  33. /// <summary>
  34. /// Multiplies the values.
  35. /// </summary>
  36. Multiply = 3,
  37.  
  38. /// <summary>
  39. /// Divides the values.
  40. /// </summary>
  41. Divide = 4
  42.  
  43. }
  44.  
  45. #endregion
  46.  
  47. #region " Entry Point (Main)"
  48.  
  49. /// <summary>
  50. /// Defines the entry point of the application.
  51. /// </summary>
  52.  
  53. public static void Main()
  54. {
  55. DoArithmetics();
  56.  
  57. }
  58.  
  59. #endregion
  60.  
  61. #region " Public Methods "
  62.  
  63.  
  64. public static void DoArithmetics()
  65. {
  66. string ExitString = string.Empty;
  67. bool ExitDemand = false;
  68. ArithmeticOperation Operation = ArithmeticOperation.None;
  69. decimal Value1 = 0m;
  70. decimal Value2 = 0m;
  71. decimal Result = 0m;
  72.  
  73.  
  74. while (!(ExitDemand)) {
  75. SetValue(ref Value1, "Ingresar el  primer numero: ");
  76. SetValue(ref Value2, "Ingresar el segundo numero: ");
  77. Console.WriteLine();
  78.  
  79. SetOperation(ref Operation, "Elegir una operacion aritmética: ");
  80. SetResult(Operation, Value1, Value2, ref Result);
  81. Console.WriteLine();
  82.  
  83. Console.WriteLine(string.Format("El resultado es: {0}", Convert.ToString(Result)));
  84. Console.WriteLine();
  85.  
  86. SetExit(ref ExitDemand, 'S', 'N', "¿Quiere salir? [S/N]: ");
  87. Console.Clear();
  88.  
  89. }
  90. // ExitDemand
  91.  
  92. }
  93.  
  94. /// <summary>
  95. /// Asks for a value and waits for the user-input to set the value.
  96. /// </summary>
  97. /// <param name="Value">The ByRefered variable to set the input result.</param>
  98. /// <param name="message">The output message.</param>
  99.  
  100. public static void SetValue(ref decimal Value, string message = "Enter a value: ")
  101. {
  102. bool Success = false;
  103.  
  104.  
  105. while (!(Success)) {
  106. Console.Write(message);
  107.  
  108. try {
  109. Value = decimal.Parse(Console.ReadLine().Replace('.', ','));
  110. Success = true;
  111.  
  112. } catch (Exception ex) {
  113. Console.WriteLine(ex.Message);
  114. Console.WriteLine();
  115.  
  116. }
  117.  
  118. }
  119. // Success
  120.  
  121. }
  122.  
  123. /// <summary>
  124. /// Asks for an arithmetic operation and waits for the user-input to set the value.
  125. /// </summary>
  126. /// <param name="Operation">The ByRefered variable to set the input result.</param>
  127. /// <param name="message">The output message.</param>
  128.  
  129. public static void SetOperation(ref ArithmeticOperation Operation, string message = "Choose an operation: ")
  130. {
  131. bool Success = false;
  132.  
  133. foreach (ArithmeticOperation Value in Enum.GetValues(typeof(ArithmeticOperation))) {
  134. Console.Write(string.Format("{0}={1} | ", Convert.ToString(Value), Value.ToString));
  135. }
  136.  
  137. Console.WriteLine();
  138.  
  139.  
  140. while (!(Success)) {
  141. Console.Write(message);
  142.  
  143. try {
  144. Operation = Enum.Parse(typeof(ArithmeticOperation), Console.ReadLine, true);
  145. Success = true;
  146.  
  147. } catch (Exception ex) {
  148. Console.WriteLine(ex.Message);
  149. Console.WriteLine();
  150.  
  151. }
  152.  
  153. }
  154. // Success
  155.  
  156. }
  157.  
  158. /// <summary>
  159. /// Performs an arithmetic operation on the given values.
  160. /// </summary>
  161. /// <param name="Operation">The arithmetic operation to perform.</param>
  162. /// <param name="Value1">The first value.</param>
  163. /// <param name="Value2">The second value.</param>
  164. /// <param name="Result">The ByRefered variable to set the operation result value.</param>
  165.  
  166. public static void SetResult(ArithmeticOperation Operation, decimal Value1, decimal Value2, ref decimal Result)
  167. {
  168. switch (Operation) {
  169.  
  170. case ArithmeticOperation.Sum:
  171. Result = Sum(Value1, Value2);
  172.  
  173. break;
  174. case ArithmeticOperation.Subtract:
  175. Result = Subtract(Value1, Value2);
  176.  
  177. break;
  178. case ArithmeticOperation.Multiply:
  179. Result = Multiply(Value1, Value2);
  180.  
  181. break;
  182. case ArithmeticOperation.Divide:
  183. Result = Divide(Value1, Value2);
  184.  
  185. break;
  186. case ArithmeticOperation.None:
  187. break;
  188. // Do Nothing
  189.  
  190. }
  191.  
  192. }
  193.  
  194. /// <summary>
  195. /// Asks for a Boolean value and waits for the user-input to set the value.
  196. /// </summary>
  197. /// <param name="ExitBool">The ByRefered variable to set the input result.</param>
  198. /// <param name="TrueChar">Indicates the character threated as 'True'.</param>
  199. /// <param name="FalseChar">Indicates the character threated as 'False'.</param>
  200. /// <param name="message">The output message.</param>
  201.  
  202. public static void SetExit(ref bool ExitBool, char TrueChar = 'Y', char FalseChar = 'N', string message = "¿Want to exit? [Y/N]: ")
  203. {
  204. bool Success = false;
  205. char Result = null;
  206.  
  207. Console.Write(message);
  208.  
  209.  
  210. while (!(Success)) {
  211. Result = Console.ReadKey().KeyChar;
  212.  
  213. switch (char.ToLower(Result)) {
  214.  
  215. case char.ToLower(TrueChar):
  216. ExitBool = true;
  217. Success = true;
  218.  
  219. break;
  220. case char.ToLower(FalseChar):
  221. ExitBool = false;
  222. Success = true;
  223.  
  224. break;
  225. default:
  226. Console.Beep();
  227.  
  228. if (!char.IsLetterOrDigit(Result)) {
  229. Console.CursorLeft = 0;
  230. SetExit(ref ExitBool, TrueChar, FalseChar, message);
  231. } else {
  232. Console.CursorLeft = Console.CursorLeft - 1;
  233. Console.Write(" ");
  234. Console.CursorLeft = Console.CursorLeft - 1;
  235. }
  236.  
  237. break;
  238. }
  239. // Char.ToLower(Result)
  240.  
  241. }
  242. // Success
  243.  
  244. }
  245.  
  246. #endregion
  247.  
  248. #region " Private Functions "
  249.  
  250. /// <summary>
  251. /// Performs a Sum operation on the specified values.
  252. /// </summary>
  253. private static decimal Sum(decimal Value1, decimal Value2)
  254. {
  255.  
  256. return (Value1 + Value2);
  257.  
  258. }
  259.  
  260. /// <summary>
  261. /// Performs a subtraction operation on the specified values.
  262. /// </summary>
  263. private static decimal Subtract(decimal Value1, decimal Value2)
  264. {
  265.  
  266. return (Value1 - Value2);
  267.  
  268. }
  269.  
  270. /// <summary>
  271. /// Performs a multiplier operation on the specified values.
  272. /// </summary>
  273. private static decimal Multiply(decimal Value1, decimal Value2)
  274. {
  275.  
  276. return (Value1 * Value2);
  277.  
  278. }
  279.  
  280. /// <summary>
  281. /// Performs a divider operation on the specified values.
  282. /// </summary>
  283. private static decimal Divide(decimal Value1, decimal Value2)
  284. {
  285.  
  286. return (Value1 / Value2);
  287.  
  288. }
  289.  
  290. #endregion
  291.  
  292. }
  293.  
  294. //=======================================================
  295. //Service provided by Telerik (www.telerik.com)
  296. //Conversion powered by NRefactory.
  297. //Twitter: @telerik
  298. //Facebook: facebook.com/telerik
  299. //=======================================================
  300.  
« Última modificación: 4 Agosto 2014, 10:23 am por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines