English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

A C program uses a structure to add two distances (in inches-feet)

Comprehensive Collection of C Programming Examples

In this example, you will learn to add two distances (inches-feet), add them together, and display the result on the screen.

To understand this example, you should understand the followingC Programming LanguageTopic:

12Inches equal1feet.

The program adds two distances in inches.

#include <stdio.h>
struct Distance {
   int feet;
   float inch;
}1, d2, result;
int main() {
   printf("Input the first distance\n");
   printf("Enter feet: ");
   scanf("%d", &d1.feet);
   printf("Enter inches: ");
   scanf("%f", &d1.inch);
   printf("\nInput the second distance\n");
   printf("Enter feet: ");
   scanf("%d", &d2.feet);
   printf("Enter inch: ");
   scanf("%f", &d2.inch);
   result.feet = d1.feet + d2.feet;
   result.inch = d1.inch + d2.inch;
   //When inches are greater than12At this time, change it to feet.
   while (result.inch > 12.0) {
      result.inch = result.inch - 12.0;
      ++result.feet;
   }
   printf("\nThe total distance = %d\'-%.1f\"", result.feet, result.inch);
   return 0;
}

Output result

Enter the first distance
Enter feet: 23
Enter inches: 8.6
Enter the second distance
Enter feet: 34
Enter inches: 2.4
The total distance = 57'-11.0"

In this program, a structure named Distance is defined. This structure has two members inch (float) and feet (int).

two variables (d1and d2),which stores two distances (inch and feet). Then, the sum of the two distances is stored in the result structure variable. If inches are greater than12If so, convert it to feet. Finally, the result is printed on the screen.

Comprehensive Collection of C Programming Examples