基本的な算術演算

CBeginner
オンラインで実践に進む

はじめに

加算、減算、乗算、除算などの算術演算は、プログラミングにおける基本演算です。この実験では、C プログラムを書いて基本的な算術演算を行う方法と、C 言語が型変換をどのように扱うかを紹介します。

基本構造を設定する

始める前に、マシンに C コンパイラがインストールされていることを確認してください。テキストエディタを開き、~/project/ ディレクトリに新しいファイルを作成して、その名前を "main.c" とします。

まずは、stdio.h ヘッダーファイルを含めて、main 関数を書きましょう。

#include<stdio.h>
int main()
{
    return 0;
}

ユーザー入力を求める

scanf() 関数を使ってユーザーに 2 つの整数の入力を求めます。これらの整数を格納する変数を int aint b として宣言します。

#include<stdio.h>
int main()
{
    int a, b;
    printf("Enter two integers: ");
    scanf("%d%d", &a, &b);

    return 0;
}

型変換なしで基本的な算術演算を行う

では、型変換なしで基本的な算術演算を行いましょう。算術演算の結果を格納する変数を addsubtractmultiply、および divide として宣言します。

#include<stdio.h>
int main()
{
    int a, b, add, subtract, multiply;
    float divide;
    printf("Enter two integers: ");
    scanf("%d%d", &a, &b);

    add = a + b;
    subtract = a - b;
    multiply = a * b;
    divide = a / b;

    printf("Addition of the numbers = %d\n", add);
    printf("Subtraction of 2nd number from 1st = %d\n", subtract);
    printf("Multiplication of the numbers = %d\n", multiply);
    printf("Dividing 1st number from 2nd = %f\n", divide);
    return 0;
}

型変換を用いた基本的な算術演算を行う

C 言語は暗黙的に型変換を行います。ただし、プログラム内で明示的に型変換を行うこともできます。型変換を使って基本的な算術演算を行う C プログラムを書いてみましょう。

算術演算の結果を格納する変数を addsubtractmultiplydivide、および remainder として宣言します。

#include<stdio.h>
int main()
{
    int a, b, add, subtract, multiply, remainder;
    float divide;
    printf("Enter two integers: ");
    scanf("%d%d", &a, &b);

    add = a + b;
    subtract = a - b;
    multiply = a * b;
    divide = a / (float)b;
    remainder = a % b;

    printf("Addition of the numbers = %d\n", add);
    printf("Subtraction of 2nd number from 1st = %d\n", subtract);
    printf("Multiplication of the numbers = %d\n", multiply);
    printf("Dividing 1st number from 2nd = %f\n", divide);
    printf("Remainder on Dividing 1st number by 2nd is %d\n", remainder);
    return 0;
}

プログラムをコンパイルして実行する

main.c ファイルを保存します。ファイルを保存した ~/project/ ディレクトリで端末を開き、次のコマンドを使ってプログラムをコンパイルします。

gcc -o main main.c

これにより、main という名前の実行可能ファイルが作成されます。次のコマンドを使ってプログラムを実行します。

./main

プログラムをテストする

2 つの整数を入力してプログラムをテストし、プログラムが期待通りの算術演算を行っているかどうかを確認します。

完全なコード

#include<stdio.h>
int main()
{
    int a, b, add, subtract, multiply, remainder;
    float divide;
    printf("Enter two integers: ");
    scanf("%d%d", &a, &b);

    add = a + b;
    subtract = a - b;
    multiply = a * b;
    divide = a / (float)b;
    remainder = a % b;

    printf("Addition of the numbers = %d\n", add);
    printf("Subtraction of 2nd number from 1st = %d\n", subtract);
    printf("Multiplication of the numbers = %d\n", multiply);
    printf("Dividing 1st number from 2nd = %f\n", divide);
    printf("Remainder on Dividing 1st number by 2nd is %d\n", remainder);
    return 0;
}

まとめ

この実験では、基本的な算術演算を行う C プログラムを書く方法と、C 言語が型変換をどのように扱うかを学びました。型変換を使っておよび使わずに基本的な算術演算を行う方法を示しました。最後に、プログラムの機能をテストするためにコンパイルして実行しました。