float answer = 1.0 / 2.0;
Remember that dividing an integer by an integer gives you an integer (1 / 2 is 0). To avoid this, divide a float by a float to get the floating point answer you expect (1.0 / 2.0 is 0.5).
float answer = 1.0 / 2.0;
float answer = 1 / 2;
Casting a float to an integer will truncate the float at the decimal point (i.e. float 1.999 becomes integer 1). If instead, you’d prefer to round to the nearest integer, use the round()
function in math.h
.
Truncation (x is 1.999, and y is 1):
float x = 1.999;
int y = (int) x;
Rounding (x is 1.999, and y is 2):
float x = 1.999;
int y = round(x);
Use the following syntax to specify the number of decimal places you’d like to print out:
float result = 1.0 / 3.0;
printf("%.5f", result);
Use the following syntax to specify the minimum number of digits you’d like to print out. The value will be padded with leading zeros if it is shorter than the number specified:
int result = 1 + 2;
printf("%03d", result);
Write a program that prompts the user to enter a temperature in Fahrenheit, converts the temperature to Celsius, and prints out the result with one decimal place.
jharvard@run.cs50.net (~): ./a.out
Temperature in F: 100
Temperature in C: 37.8
#include <cs50.h>
#include <stdio.h>
int main(int argc, string argv[])
{
// TODO: prompt user for temp in F, convert to C, print result
}
Write a program that prompts the user for a non-negative numerator and a positive denominator and prints the fraction as a percent to two decimal places.
jharvard@run.cs50.net (~): ./a.out
non-negative numerator: 1
positive denominator: 2
50.00%
#include <cs50.h>
#include <stdio.h>
int main(int argc, string argv[])
{
// TODO: prompt user for fraction, convert to %, print %
}