TL; DR:
型convert_type
を扱っているときでも、情報を失うことなく型キャストを行うことができる型(名前を付けましょう)はありますfloat
か?
使用例:
float f1 = 12.34;
long i1 = 32;
convert_type tmp1 = (convert_type) f;
convert_type tmp2 = (convert_type) i;
float f2 = (float) tmp1; // should be 12.34
long i2 = (long) tmp2; // should be 32
環境 :
そのような関数を作成したい:
convert_type ask(char* question, val_type input_type)
val_type
によって定義されたタイプで:
typedef enum {
INT_T,
STR_T,
CHAR_T,
FLOAT_T
} val_type;
引数にquestion
は、入力を求めるために出力する文字列があります。
この関数のアイデアはstdin
、タイプの入力をinput_type
要求し、入力が有効になるまで再度要求することです。
使用例ask()
:
int main(int argc, char const *argv[]) {
int nb = (int) ask("How many tries to you want ?\n --> ", T_INT);
char * message = (char*) ask("What is the victory message ?\n --> ", T_STR);
float prob = (float) ask("What is the probability of winning ?\n --> ", T_FLOAT);
printf("\n\n");
printf("Number of tries : %d\n", nb);
printf("Victory message : %s\n", message);
printf("Probability : %f\n", prob);
return 0;
}
タイプを使用して実装しましたが、タイプunsigned long
に問題がありfloat
ます。
実行例:
How many tries to you want ?
--> many
The input must be a valid integer.
How many tries to you want ?
--> -2131
What is the victory message ?
--> We are the champions !!!
What is the probability of winning ?
--> 3.4.3
The input must be a valid float value.
What is the probability of winning ?
--> 2.54
Number of tries : -2131
Victory message : We are the champions !!!
Probability : 2.000000
タイプではunsigned long
うまく機能しないことがわかりますfloat
(unsigned longには整数値が含まれているために2.54
なりまし2.00
た)。
代わりにどのタイプを使用できますか?
読み取り/書き込みタイプの不一致を引き起こさないように十分注意している場合は、次を使用してunion
次のようにすることができます。
#include <stdio.h>
typedef union {
int int_data;
char* str_data;
char char_data;
float float_data;
} convert_type;
typedef enum {
INT_T,
STR_T,
CHAR_T,
FLOAT_T
} val_type;
convert_type ask(char* question, val_type input_type) {
static char[] str = "We are the champions !!!";
convert_type ret;
fputs(question, stdout);
/* this is examples of how to set values. reading is omitted. */
switch (input_type) {
case INT_T:
ret.int_data = -2131;
break;
case STR_T:
ret.str_data = str;
break;
case CHAR_T:
ret.char_data = 'a';
break;
case FLOAT_T:
ret.float_data = 2.54;
break;
}
return ret;
}
int main(int argc, char const *argv[]) {
int nb = ask("How many tries to you want ?\n --> ", INT_T).int_data;
char * message = ask("What is the victory message ?\n --> ", STR_T).str_data;
float prob = ask("What is the probability of winning ?\n --> ", FLOAT_T).float_data;
printf("\n\n");
printf("Number of tries : %d\n", nb);
printf("Victory message : %s\n", message);
printf("Probability : %f\n", prob);
return 0;
}
とは異なりstruct
、のメンバーはunion
1つのメモリスペースを共有します。したがって、のメンバーに値を書き込むunion
と、のメンバーはunion
無効になります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加