Variables, types, and arithmetic · Variables, tipos y aritmética
Every value has a type
- In C, every variable has a type that says what kind of value it holds.
- The three you use most:
int(a whole number),double(a number with a decimal point), andchar(a single character). - You must give the type when you create the variable:
int n = 5;ordouble pi = 3.14;.
Cada valor tiene un tipo
- En C, cada variable tiene un tipo que indica qué clase de valor contiene.
- Los tres que más usas:
int(un número entero),double(un número con punto decimal) ychar(un solo carácter). - Debes especificar el tipo al crear la variable:
int n = 5;odouble pi = 3.14;.
Doing arithmetic
- C does math with
+,-,*, and/, just like a calculator. *and/happen before+and-. Use brackets( )to change the order.- The
%operator gives the remainder of a division:17 % 5is2.
Realizar operaciones aritméticas
- C realiza matemáticas con
+,-,*y/, igual que una calculadora. *y/se ejecutan antes que+y-. Usa paréntesis( )para cambiar el orden.- El operador
%da el resto de una división:17 % 5es2.
Integers divide differently
- When you divide two
ints, C throws away the fraction:7 / 2is3, not3.5. - To keep the fraction, at least one side must be a
double.7 / 2.0is3.5. - You can cast an
intto adoublewith(double):(double)sum / count.
La división de enteros funciona diferente
- Cuando divides dos
ints, C descarta la fracción:7 / 2es3, no3.5. - Para mantener la fracción, al menos uno de los lados debe ser un
double.7 / 2.0es3.5. - Puedes hacer un cast (conversión) de un
inta undoublecon(double):(double)sum / count.
Reading input
scanfreads typed input into a variable.scanf("%d", &n);reads oneintinton.- Note the
&beforen:scanfneeds the address of the variable so it can fill it in. - In this playground, Run first asks you for the input, one value per line; Check answer feeds the example input for you.
Leer entrada
scanflee datos ingresados por teclado en una variable.scanf("%d", &n);lee unintenn.- Nota el
&antes den:scanfnecesita la dirección de la variable para poder asignarle un valor. - En este entorno de práctica, Run primero te pedirá la entrada, un valor por línea; Check answer introduce automáticamente la entrada del ejemplo.
#include <stdio.h>
int main(void) {
int a = 7, b = 2;
printf("%d\n", a / b); // 3 (integer division)
printf("%.1f\n", a / 2.0); // 3.5 (one side is a double)
printf("%d\n", a % b); // 1 (remainder)
return 0;
}
Common mistakes
- Declare a variable with its type:
int n;. - Integer division truncates:
7 / 2is3, not3.5.
Errores comunes
- Declara una variable con su tipo:
int n;. - La división de enteros trunca:
7 / 2es3, no3.5.
Now you try
- Use
/and%for whole-number math, and adouble(or a cast) when you need a fraction. - For the function tasks, do not write a
main— the checker provides one. - Press Run to compile and run, then Check answer.
Ahora tú intentas
- Usa
/y%para matemáticas con números enteros, y undouble(o un cast) cuando necesites una fracción. - Para las tareas de funciones, no escribas un
main— el validador proporciona uno. - Presiona Run para compilar y ejecutar, luego Check answer.
Variables hold a value · Las variables almacenan un valor
A variable is a named box of a fixed type; assigning replaces it. · Una variable es una caja con nombre de un tipo fijo; asignar reemplaza su contenido.
Read one integer n with scanf. A box holds 6 items. Print two lines exactly: Full boxes: then the value of n / 6, and Left over: then the value of n % 6. · Lea un entero n con scanf. Una caja contiene 6 elementos. Imprima dos líneas exactamente: Full boxes: seguido del valor de n / 6, y Left over: seguido del valor de n % 6.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete double average3(int a, int b, int c) so it returns the average of the three as a double. Watch out for integer division — divide by 3.0, not 3. Do not · no write a main. · Complete double average3(int a, int b, int c) para que devuelva el promedio de los tres como double. Tenga cuidado con la división entera: divida por 3.0, no por 3. No escriba un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write double hyp(double a, double b) that returns the hypotenuse length: the square root of a*a + b*b. Use sqrt from <math.h>. Do not · no write a main. · Escriba double hyp(double a, double b) que devuelva la longitud de la hipotenusa: la raíz cuadrada de a*a + b*b. Use sqrt de <math.h>. No escriba un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.