Cプログラミング
 Computer >> コンピューター >  >> プログラミング >> Cプログラミング

C数値を文字列に変換するプログラム


このセクションでは、数値(整数、浮動小数点数、またはその他の数値型データ)を文字列に変換する方法を説明します。

ロジックは非常に単純です。ここでは、sprintf()関数を使用します。この関数は、値または行を文字列に出力するために使用されますが、コンソールでは使用されません。これは、printf()とsprintf()の唯一の違いです。ここで、最初の引数は文字列バッファです。データを保存したい場所。

Input: User will put some numeric value say 42.26
Output: This program will return the string equivalent result of that number like "42.26"

アルゴリズム

Step 1: Take a number from the user
Step 2: Create an empty string buffer to store result
Step 3: Use sprintf() to convert number to string
Step 4: End
サンプルコード

#include<stdio.h>
main() {
   char str[20];    //create an empty string to store number
   float number;
   printf("Enter a number: ");
   scanf("%f", &number);
   sprintf(str, "%f", number);   //make the number into string using sprintf function
   printf("\nYou have entered: %s", str);
}

出力:

Enter a number: 46.3258
You have entered: 46.325802

  1. 日を月と日数に変換するCプログラム

    ユーザーは合計日数を入力する必要があります。合計日数を月に変換し、翌月の残りの日数に変換する必要があります。 日を月に変換する式は次のとおりです- 月=日/30 次の月の残りの日を見つけるロジックは次のとおりです- 日=日%30 アルゴリズム 日を月と日数に変換するには、以下のアルゴリズムを参照してください。 Step 1: Start Step 2: Declare month and days Step 3: Read total number of days Step 4: Compute months    months=days/30 Step 5:

  2. 与えられた数を単語に変換するCプログラム

    数値で構成される文字列が与えられた場合、タスクはそれらの与えられた数値を単語で隠すことです。 入力「361​​」があるように。その場合、出力は「三百六十一」という言葉である必要があります。次の問題を解決するには、1、数万、数千などの数と場所を覚えておく必要があります。 コードは最大4桁の数字、つまり0〜9999のみをサポートします。したがって、入力は0〜9999である必要があります。 場所が-のようになるように1,111を考えてみましょう 例 Input: “1234” Output: one thousand two hundred thirty four