C/Data Type/Constant
Содержание
Calculate a discounted price
#include <stdio.h>
int main()
{
const int level1 = 30;
const int level2 = 50;
const double discount1 = 0.10;
const double discount2 = 0.15;
const double unit_price = 3.50;
int q1 = 0;
int q2 = 0;
int qty_over_level1 = 0;
int qty_over_level2 = 0;
printf("Quantity?: ");
scanf("%d", &q1);
q2 = q1;
qty_over_level2 = q1%level2;
q1 -= qty_over_level2;
qty_over_level1 = q1%level1;
q1 -= qty_over_level1;
printf("\nThe total price for %d is $%.2lf\n", q2,
unit_price*(q1+(1.0-discount1)*qty_over_level1+(1.0-discount2)*qty_over_level2));
}
Cannot assign value to a constant variable
#include <stdio.h>
int main(void)
{
const int i = 10;
i = 20; /* this is wrong */
printf("%d", i);
return 0;
}
Convert inches to yards, feet, and inches
#include <stdio.h>
void main()
{
int inches = 0;
int yards = 0;
int feet = 0;
const int inches_per_foot = 12;
const int feet_per_yard = 3;
printf("Enter a distance in inches: ");
scanf("%d", &inches);
feet = inches/inches_per_foot;
yards = feet/feet_per_yard;
feet %= feet_per_yard;
inches %= inches_per_foot;
printf("That is equivalent to %d yards %d feet and %d inches.\n",
yards, feet, inches);
}
Define a constant value
#include <stdio.h>
int main(void)
{
const int i = 10;
printf("%d", i);
return 0;
}