2016-09-02 21 views
-3

a ± biフォームの文字列をint Realint Imに変換する必要があります。文字列がその形式でない場合は、エラーを出力します。 aをintに変換し、bに変換するアイデアがありますが、それが肯定的であれば、虚数で何をするのか分かりません。文字列 "a±bi"から数字C

すなわち

0,034 - 1,2i 

>a=0,034 
>b=-1,2 

0,25 

>Error, you must write in "a±bi" form 

3,234 + 34,43i 

>a=3,234 
>b=34,43 

PS:私はこのlinkを見つけたが、それはC++であると私はそれが

EDITやっているのか分からない:実数はプラスまたはマイナスを持つことができます。

+1

@Shahid数値の整数部分と小数部分を区切るための期間の一般的な代替方法です。 –

+3

これまでに何を書いていますか? –

+2

整数として0.034のような10進数をどのように格納すると思いますか? – duskwuff

答えて

0

これは、C-標準はあなたが必要なすべてを持っている、非常に簡単です:

#include <stdio.h> 
#include <stdlib.h> 

#define BUFFER_SIZE 100 

// ALL CHECKS OMMITTED! 

int main() 
{ 
    double a, b; 
    char buffer[BUFFER_SIZE]; 
    int count = 0; 
    char c; 
    char *endptr; 

    while ((c = fgetc(stdin)) != EOF) { 
    if (c == '\n') { 
     // make a proper C-string out of it 
     buffer[count] = '\0'; 
     // reset counter for the next number 
     count = 0; 
     // strtod() is intelligent enough to 
     // stop at the end of the number 
     a = strtod(buffer, &endptr); 
     // endptr points to the end of the number 
     // skip whitespace ("space" only) 
     while (*endptr == ' ') { 
     endptr++; 
     } 
     // skip the +/- in the middle 
     endptr++; 
     // strtod() skips leading space automatically 
     b = strtod(endptr, NULL); 
     printf("a = %g, b = %g\n", a, b); 
    } 
    // read all into a big buffer 
    buffer[count++] = (char) c; 
    if (count >= BUFFER_SIZE) { 
     fprintf(stderr, "Usage: type in complex numbers in the form \"a + b\"\n"); 
     exit(EXIT_FAILURE); 
    } 
    } 

    exit(EXIT_SUCCESS); 
} 

参照してください?心配する必要はありません。

+0

プログラムが失敗して終了する唯一のケースは、読み込んでいる行がバッファサイズよりも大きい場合です。手紙を書くのはどうですか? –

+0

@AgustinLuquesその理由は、このコードの先頭にこのオールキャップのメモがあるからです。「すべてチェックしてください! (スペルチェック;-)を含む)。 'strtod()'の返り値とエラーをチェックするか(例えばコード例の 'strtol()'のマンページを参照)、適切な浮動小数点数であれば入力をチェックしてください。 'strtod()'のチェックはずっと簡単です。 – deamentiaemundi

+0

コードが途中で+/-をスキップするため、OPの目標を達成できません。これは誤った入力を検出するだけでなく、「b」の正しい形成に必要である。 '0,034 - 1,2i'を試してみてください。 – chux

0

使用sscanf()

"%lf"スキャン0以上の空白、その後スキャンdouble
" "スキャン0以上の空白
"%1[+-]"からなる非空の文字列をスキャン+または-だけアップ1文字の長さです。
"i"のスキャンiの文字
"%n"これまでにスキャンされた文字の数を格納します。 (返り値には加算されません)。

#include <complex.h> 
#include <stdio.h> 

double complex ALconvert(const char *s) { 
    int n = 0; 
    double re, im; 
    char sign[2]; 

    if (sscanf(s, "%lf %1[+-] %lf i %n", &re, sign, &im, &n) != 3 || s[n]) { 
    puts("Error, you must write in \"a+/-bi\" form"); 
    return 0.0/0.0; // TBD_ErrorCode; 
    } 
    if (sign[0] == '-') { 
    im = -im; 
    } 
    return re + im*_Complex_I; 
} 
関連する問題