You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
2 Hrs
51 Min
48 Seg

Trabajando con números y operadores aritméticos

10/26
Resources

How to correctly handle data types in programming?

Properly handling data types in your program is an essential skill for any developer, since an error in the data type can cause all the information in your program to be corrupted. Imagine that you are setting up a program to handle values that should range from -10 to 10. If you limit a variable so that it does not recognize negative values, you will lose much of the important information. Next, we will explore how to properly handle data types and arithmetic operators in C#.

How do we start a C# project to calculate the area of a rectangle?

Starting a project in C# to perform calculations can be fairly straightforward. First, open a new project of type "Console Application" and name it, for example, "Square Area". We start by declaring and assigning values to our variables:

// This program calculates the area of a rectangleint sideA = 10;int sideB = 20;
// Calculating the area of the rectangleint area = sideA * sideB;
Console.WriteLine("The area of the rectangle is: " + area);

In this code snippet, you can see the use of multiplication to calculate the area of the rectangle using the sideA and sideB variables.

What happens when working with different data types such as float and int?

When performing operations between different data types such as float and int, you may encounter warnings or errors in your code. The compiler will tell you if you are trying to convert or operate incorrectly with incompatible types.

float sideA = 10.2f;int sideB = 20;float area = sideA * sideB;

When multiplying a float by an int, it is imperative that the receiving variable, in this case area, is also of type float to avoid loss of decimal information.

How do arithmetic operators work in C#?

Arithmetic operators are fundamental to perform mathematical operations in programming. There are several operators that you should know:

  • Addition (+): adds two operands together.
  • Subtraction (-): subtract one operand from the other.
  • Multiplication (*): multiplies two operands.
  • Division (/): divides one operand by another.
  • Modulus (%): obtains the remainder of the division.
  • Increment (++): increases the value of a variable by 1.
  • Decrement (--): decreases the value of a variable by 1.

Example of use of increment and decrement

Imagine that you want to increment a variable several times in a row. Let's analyze how it acts in a loop:

int sideB = 1; sideB++; // sideB is now 2 sideB++; // sideB is now 3 sideB--; // sideB is now 2.

In this example, the use of ++ and -- shows you how these operations can modify the value of sideB.

How to improve console output with strings?

To make the console output more readable, it is advisable to use strings that provide additional information to the user. Example:

Console.WriteLine("The area of the rectangle is: " + area);

This code fragment concatenates an informative message together with the calculated value of the area, making the result more understandable.

What are the next steps in handling data in a program?

After learning how to handle data types and arithmetic operators, it is time to move on to user interaction. This includes allowing the user to enter data into the program, handling text and numbers that the user enters, which we will cover in the next class. Keep exploring and practicing to hone your skills!

Contributions 33

Questions 5

Sort by:

Want to see more contributions, questions and answers from the community?

Este profe y el argentino deberian ser los que presentan los videos de la plataforma, se les entiende claro, no echan tanto rollo, hay otros que seran muy buenos en el area pero para dar los tutoriales no traen nada.

Para comentar código en una sola línea se escribe dos barras diagonales ** “//”.**
Para la variables tipo flotante en C#, hay que agregarle una “f” al final de cada valor. Ejm:
float valor = 10.0f

Operador de Suma: +
Operador de Resta: -
Operador de División: /
Operador de Multiplicación: *
Operador para sacar Módulo: %
Operador para incrementar: ++
Operador para decrementar: –

Si escriben cw y dos veces tab les crea todo el Console.WriteLine();
Y asi evitan cansar sus manitas jajajaja

Por si quieren revisar cada uno de estos operadores aritméticos: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators :smile

static void Main(string[] args)
        {
            //rectangle area calc.
            
            //rectangle values
            double sideA = 10.0;
            int sideB = 1;

            sideB++;
            sideB++;
            sideB++;
            sideB--;

            //rectangle area formula is a*b
            double area = sideA * sideB;


            Console.WriteLine("The rectangle area is: " + area);
        }

en el minuto 7:40 el profe aplicó la metodología de Dora la Exploradora jajajaja

Acá les dejo como hice el cálculo del área de un cuadrado:

using System;

namespace SquareArea
{
    class Program
    {
        static void Main(string[] args)
        {
            // Variables
            int sideA, sideB;    

            Console.WriteLine("Bienvenido a mi segundo programa");
            Console.WriteLine("Cálcularemos el área de un cuadrado");

            // Solicitar al usuario los datos a trabajar:
            Console.WriteLine("Ingrese el lado A");
            sideA = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Ingrese el segundo lado de su cuadrado");
            sideB = Convert.ToInt32(Console.ReadLine());

            // Mostrar resultado al usuario
            int squareArea = sideA * sideB;

            Console.WriteLine("*** Resultado ***");
            Console.WriteLine(squareArea);


		    		
	    }
    }
}

Repasando ando…

int sideA = 10;
int sideB = 20;
// rectangle area formula es a*b
int area = sideA * sideB;
Console.WriteLine("The area of the rectangule is :" + area + "\n Side a: " + sideA + "\n Side b: " + sideB);

float sideA1 = 10.5f;
float sideB1 = 20.58f;
sideB1++;
sideA1--;
// rectangle area formula es a*b
float area1 = sideA1 * sideB1;
Console.WriteLine("The area of the rectangule is :" + area1 + "\n Side a: " + sideA1 + "\n Side b: " + sideB1);
//rectangle area calc
//rectangle values
float sideA = 10.1f;
int sideB = 1;
sideB++;
sideB++;
sideB--;

//rectangle area formula is a*b
float area =sideA * sideB;

Console.WriteLine("The rectangle area is: "+area);    

class Program
    {
        static void Main(string[] args)
        {
            //rectangle area calc.

            //rectangle values
            double sideA = 10.0;
            int sideB = 1;

            sideB++; // 2
            sideB++; // 3
            sideB++; // 4
            sideB--; // 3

            //rectangle area formula is a*b
            double area = sideA * sideB;
            Console.WriteLine("The rectangle area is: " + area);

            //Nota
            //float valor = 10.0f  as los valores float se les agrega la f
            //Operador de Suma: +
            //Operador de Resta: -
            //Operador de División: /
            //Operador de Multiplicación: *
            //Operador para sacar Módulo: %
            //Operador para incrementar: ++
            //Operador para decrementar: –
        }
    }

namespace squareArea
{
internal class Program
{
static void Main(string[] args)
{
//area de rectangulo pdeir datos
Console.WriteLine(“Escribe Lado A”);
float sideA = float.Parse(Console.ReadLine());

        Console.WriteLine("Escribe Lado B");
        float sideB = float.Parse(Console.ReadLine());
        //FORMULA DE RECTANGULO
        float result = sideB * sideA;
        //MOSTRAR RESULTADO

        Console.WriteLine("The Result" + " " + result);
    }
}

}
//Mi splucion a lo propuesto 😄

Operadores aritméticos

Primero que nada hagamos recordemos algunas cosas:

  • Podemos comentar en el editor con //, lo que permite ingresar anotaciones para nosotros y otros colaboradores con los que estemos trabajando. Dichos comentarios no afectan a la ejecución del código y también pueden servir para sacar alguna porción de nuestro trabajo para que no se ejecute pero sin necesidad de borrarlo (ejemplo: comentamos un string porque aún no lo usaremos pero no lo queremos eliminar)

  • El doble slash sirve para comentar UNA línea pero no si queremos hacer saltos de línea. En este último caso lo haremos con /* */

/* Acá escribo cosas
poque no sé qué poner
Ejemplo
 */
           string cosaAlgo = "Y cerramos";
  • Cómo se llama esta forma de escribir los nombres de las variables? Exacto, camelCase🐫. No es una obligación, sólo un consenso que es mejor respetar en C#

AHORA SÍ. Originalmente las computadoras se usaban para realizar calculos muy bestiales por lo que tenemos a disposición multitud de signos que podemos usar para nuestros cálculos:

  • Suma: +
  • Resta: -
  • Multiplicación: *
  • División: /
  • Módulo o Resto (lo que te quedaba de una división): %
  • Incremento (sería un +1): ++
  • Decremento (-1): –

Y te acordás de los paréntesis () y del orden de prioridad de las operaciones❓ Bien, pequeño Timmy, acá también se aplican. Las multiplicaciones y divisiones se resuelven antes que las sumas y restas, pero lo que está entre paréntesis se resuelve primero y si es una multiplicación o una resta entre paréntesis se resuelve aún antes más primero que todo lo otro.
Ya está? Ya me puedo ir?
No no, Timmy. Aún hay algo más.
En ocasiones ocurrirá que tenés ganas de multiplicar (o sumar, o dividir; lo que sea) int con float pensando en obtener un resultado int pero dará error. La razón? Porque quizás el resultado es un decimal (float == decimal E int == enteros positivos o negativos) y en ese caso tendremos que colocar un añadido a nuestra variable:

float sideA = 10.7f;
int sideB = 20;

float area = sideA * sideB;

Console.WriteLine(area);

Con esto conseguimos que:

  1. sideA sea reconocido como un valor float y el punto (no coma, punto .) no sea leído como un error
  2. Asignamos el tipo float al valor area porque el resultado de dicha multiplicación podría ser decimal.

"Eso es todo?"
Casi, Timmy, casi. También tenemos los clásicos "mayor que ", "menor que ", "igual o mayor que " (>, <, =>, =<) pero todo eso es aparte. No te hagas lío aún. Lo importante es que sepas que los operadores existen y que hay un orden a respetar al momento de resolver ecuaciones más o menos complejas.

Es inevitable para mi pensar en el WriteLine() como en el console.log() de C#

Este seria el codigo si es que quisieras preguntar los lados ![](https://static.platzi.com/media/user_upload/image-9df93da5-3164-4ffa-a297-f5996f2383b9.jpg)

Como un pequeño aporte para incrementar el valor de una variable en una cantidad especifica o para restarlo pueden usar este tipo de incrementador al igual que en Java:

sideB += 5; 
sideB -= 5;

using System;
namespace squarearea
{
class Program
{
static void Main(string[] args)
{
// area rectangle
Console.WriteLine(“Input the side A:”);
double sideA = float.Parse(Console.ReadLine());
Console.WriteLine(“Input the side B:”);
double sideB = float.Parse(Console.ReadLine());
// formule area rectangle
double area = sideA * sideB;
//resultado
Console.WriteLine(“The result area rectangle is:” + area);
}
}
}

// See https://aka.ms/new-console-template for more information
Console.WriteLine(“ingresar el area de terreno”);

// este programa calcula el area de un terreno
int sidea ;
int sideb ;

sidea= Convert.ToInt32(Console.ReadLine());
sideb= Convert.ToInt32(Console.ReadLine());
// formula a *b;
int areas = sidea * sideb;

Console.WriteLine(areas);

Los operadores son similares a JS, estuve avanzando mucho con c#, tenia miedo al prioncipio ya que que diferente,o eso pensaba, con JS conceptos, me fue mas facil.

Sabia que el ++ aumentaba , pero no sabia que se podia usar asi.

Algunas operaciones con valores numericos:

using System;
namespace _10_OperadoresLogicos
{
    class Program
    {
        static void Main()
        {
            float a = 5.5f;
            float b = 2.5f;
            float c = a * b;

            /*** Suma ***/
            Console.WriteLine("\n*** Suma ***");
            Console.WriteLine($"a + b + c = { a + b + c }");
            Console.WriteLine($"c + a + b = { c + a + b }");
            /*** Resta ***/
            Console.WriteLine("\n*** Resta ***");
            Console.WriteLine($"a - b - c = { a - b - c }");
            Console.WriteLine($"c - a - b = { c - a - b }");
            /*** Multiplicacion ***/
            Console.WriteLine("\n*** Multiplicacion ***");
            Console.WriteLine($"a * b * c = { a * b * c }");
            Console.WriteLine($"c * a * b = { c * a * b }");
            /*** Division ***/
            Console.WriteLine("\n*** Division ***");
            Console.WriteLine($"a / b / c = { a / b / c }");
            Console.WriteLine($"c / a / b = { c / a / b }");
            /*** Diversas operaciones ***/
            Console.WriteLine("\n*** Diversas operaciones ***");
            Console.WriteLine($"a * b + c = { a * b + c }");
            Console.WriteLine($"c + a * b = { c + a * b }");
            /*** Diversas operaciones ***/
            Console.WriteLine("\n*** Diversas operaciones ***");
            Console.WriteLine($"a * (b + c) = { a * (b + c) }"); // Resuleve primero la suma y despues la multiplicacion
            Console.WriteLine($"(c + a) * b = { (c + a) * b }"); // Resuleve primero la suma y despues la multiplicacion
        }
    }
}

Y el resultado en consola:

*** Suma ***
a + b + c = 21.75
c + a + b = 21.75

*** Resta ***
a - b - c = -10.75
c - a - b = 5.75

*** Multiplicacion ***
a * b * c = 189.0625
c * a * b = 189.0625

*** Division ***
a / b / c = 0.16
c / a / b = 1

*** Diversas operaciones ***
a * b + c = 27.5
c + a * b = 27.5

*** Diversas operaciones ***
a * (b + c) = 89.375 // Soluciona primero la suma
(c + a) * b = 48.125 // Soluciona primero la suma

Mi código con validación de que solo se ingrese número y si no se ingresa se le dice al usuario y se vuelve a repetir la operacíón:

        double lado = 0;
        bool salida = true;

        while (salida == true)
        {

            try
            {
                Console.WriteLine("A continuación, se calculará el área de un cuadrado");
                Console.WriteLine("Ingresa un de los lados del cuadrado");
                string x = Console.ReadLine();
	   //esto permite que si la variable x no es un número se lance el mensaje del problema de las letras
                lado = double.Parse(x);
                                         //Base - exponente 
                double resultado = Math.Pow(lado, 2);
                Console.WriteLine("El área del cuadrado es: " + resultado);

                Console.WriteLine("----------------------------------------------------------");
                Console.WriteLine("Ahora se calculará el área de un rectangulo");
                Console.WriteLine("Ingresa Base (b)");
                double b = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("Ingresa Altura (a)");
                double a = Convert.ToDouble(Console.ReadLine());

                double resultado2 = a * b;
                Console.WriteLine("El área del rectangulo es: " + resultado2);
                salida = false;
            }
            catch (Exception)
            {

                Console.WriteLine("No es un número, ingresa un número");
                salida = true;
            }

        }

¿Qué pasa si hago esto?

int numero = 10;
Console.WriteLine(numero++); //¿Que valor imprime y por que?

excelente profesor

using System;

namespace _7SquareArea
{
    internal class Program
    {
        static void Main(string[] args)
        {

            //Este programa calcula el area de un rectangulo

            //Rectangle values
            int height;
            int width;
            int largo;

            //Pedimos al usuario que nos de los datos
            Console.WriteLine("Ingrese el largo del rectangulo: ");
            height = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Ingrese el ancho del rectangulo: ");
            width = Convert.ToInt32(Console.ReadLine());
  
            //Rectangle area a*b
            int area = height * width;
            Console.WriteLine("El area de tu rectangulo es: " + area);
        }
    }
}

Ctrl + K + Ctrl + C
Para comentar

static void Main(string[] args)
{
// Title of the program
Console.Title = “Square Area”;
Console.WriteLine("=");
Console.WriteLine(" Square, Circle, Triangle Calculation Area “);
Console.WriteLine(”
=");

        // Ask the user for the number of sides of the shape


        Console.WriteLine("What figure do you want to calculate the area?");
        
        Console.WriteLine("1. Square");
        Console.WriteLine("2. Circle");
        Console.WriteLine("3. Triangle");

        // Ask the user to enter the figure

        int figure = Convert.ToInt32(Console.ReadLine());

        // If the user enter 1, the program will calculate the area of a square

        if (figure == 1)
        {
            Console.WriteLine("Enter the value of the side of the square");
            double side = Convert.ToDouble(Console.ReadLine());
            double area = side * side;
            Console.WriteLine("The area of ​​the square is: " + area);
        }
        else if (figure == 2)
        {
            Console.WriteLine("Enter the value of the radius of the circle");
            double radius = Convert.ToDouble(Console.ReadLine());
            double area = Math.PI * radius * radius;
            Console.WriteLine("The area of ​​the circle is: " + area);
        }
        else if (figure == 3)
        {
            Console.WriteLine("Enter the value of the side of the triangle");
            double side = Convert.ToDouble(Console.ReadLine());
            double area = (side * side) / 2;
            Console.WriteLine("The area of ​​the triangle is: " + area);
        }
        else
        {
            Console.WriteLine("Enter a valid value");               
        }

        Console.ReadKey();
    }

no tenia idea de lo de la f, interesante!!

Excelente clase

Image

Code

using System;

namespace RectangleArea
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, input the rectangle area!\n");
            Console.Write("Rectangle Height: ");
            double rHeight = Convert.ToDouble(Console.ReadLine());
            Console.Write("Rectangle Width: ");
            double wWidth = Convert.ToDouble(Console.ReadLine());
            double rectangleArea = rHeight * wWidth;
            Console.WriteLine("\n****Without Rounding****");
            Console.WriteLine("The rectangle area is: " + rectangleArea);
            Console.WriteLine("\n****With Rounding***");
            Console.WriteLine("The rectangle area is: " + Math.Round(rectangleArea, 2));
        }
    }
}

muy bien explicado