getchar()メソッドを使用して数値を浮動小数点数に変換して問題を解決するのに問題があります。私の問題では、文字をの配列に格納する必要がありfixed size = 50
ます。また、配列への格納は、getchar()を使用して読み取られたスペース' '
または改行がある場合にのみ発生します\n
。これは、EOFが読み取られるまで発生します。最後に、float番号とそのdouble(タブスペース付き)が返され、printf
。を使用して出力されます。
指示に従って、getchar()のみが許可されます。関数が好きscanf()
、fgets()
、atoi()
、atol()
、atof()
、strtol()
、strtoul()
または余分な配列を使用することはできません。
これが私が今まで思いついたものです。(下部のサンプル入力と出力を参照してください)
#include <stdio.h>
#define SIZE 50 // assume no more than 50 literals in input
int main(){
float c;
float u;
float value = 0.0;
float resu[SIZE];
int index = 0;
int i;
char sub = '0';
value = 0;
c = getchar();
while ( c != EOF){
if(c == '.'){
u = 0.1;
}
else if (c == ' ' || c == '\n'){
if(u == 0.1){
value = value * 0.1;
}
resu[index] = value;
index++;
value = 0;
}
if( c >= '0' && c <= '9'){
value = value * 10 + (c-sub);
}
c = getchar(); // read next
}
//printing the result
for(i=0; i < index; i++)
printf("%.4lf \t %.4lf\n", resu[i],resu[i] *2.0);
return 0;
}
(注-元の番号と2倍の間にタブがあります)
Sample Input:
2.3 4.56
43.3 43 5.3
.3 1.2
Sample Output:
2.3000 4.6000
45.6000 91.2000 //ERROR
43.3000 86.6000
4.3000 8.6000 //ERROR
5.3000 10.6000
0.3000 0.6000
1.2000 2.4000
あなたがしない2つのことは、各単語の初期化u
またはリセットu
です。
float u = 0;
....
else if (c == ' ' || c == '\n') {
if (u == 0.1){
value = value * 0.1;
}
resu[index] = value;
index++;
value = 0;
u = 0; // Reset it for next number
}
また、ハードコーディングしますがu = 0.1
、これは小数点以下1桁しかない場合にのみ機能します。この割り当てでは問題ないかもしれませんが、小数点以下の桁数を数える方がよいでしょう。
#include <stdbool.h>
#include <math.h>
#include <ctype.h>
...
int digits_after_decimal = 0;
bool have_decimal_point = false;
int value = 0;
int c;
while ((c = getchar()) != EOF) {
// Decimal point found?
if ('.' == c) {
have_decimal_point = true;
}
else if (isdigit(c)) {
// Add this digit to integer value
// Parentheses not required but added for clarity
value = (value * 10) + (c - '0');
// If decimal point already found, increment count
if (have_decimal_point) digits_after_decimal += 1;
}
// Complete word. Save and reset
// TODO: Multiple spaces between words?
else if (' ' == c || '\n' == c) {
// Divide by the correct power of 10 based on
// the number of digits after the decimal point
resu[index++] = value / pow(10, digits_after_decimal);
if (index == SIZE) break; // Avoid overflow
// Reset for next number
digits_after_decimal = 0;
have_decimal_point = false;
value = 0;
}
// TODO: Negative numbers?
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加