0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

数値と計算

Last updated at Posted at 2021-02-08

数値の表示

printf()を利用し、ダブルコーテーション(")で囲まれた文字列を出力します。

//C
# include <stdio.h>

int main(void){
    printf("犬が好き");//犬が好きと出力する
}

それと同じ容量で、数値を記載すればその数値が出力されます。

//C
# include <stdio.h>

int main(void){
    printf("3");//3と出力する
}

でも、これはあくまで文字列として出力されたものであり、とても計算に使えたものではないでしょう。そこで__フォーマット指定子__というものを利用します。
フォーマット指定子とは、値を置き換えて出力するための記号のことです。

printf("%d", x);//数値xを出力する

ここでは、%d__がフォーマット指定子です。decimal(10進数)という意味で、整数の値を%d__と置き換えています。その後ろに__,(コンマ)__で区切って記載した値を出力することができます。

計算

フォーマット指定子を利用すれば、以下のように計算を行うことができます。

# include<stdio.h>

int main(void){
    printf("3たす7は%dです\n", 3+7);//足し算は+を利用
    printf("8ひく5は%dです\n", 8-5);//引き算は-を利用
    printf("2かける6は%dです\n", 2*6);//掛け算は*を利用
    printf("20わる4は%dです\n", 20/4);//割り算は/を利用
    printf("30わる9のあまりは%dです\n", 30%9);//割り算をした際の余りを求めるときは%を利用
}

このコードの実行結果が以下の通りです。
image.png

また、複数の値を__%d__で置き換えることも可能です

# include<stdio.h>

int main(void){
    printf("%dたす%dは%dです",3,7, 3+7);
//1個目の%dには3、2個目の%dには7、3個目の%dには3+7の解である10が代入される
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?