2017-05-13 1 views
0

私はC言語で新しく、ループと文字を使用すると思いますが、私はではありません。 allloudは文字列、配列、関数を使用しています。Cのチリング文字C

記号 '#'と記号 '$'との間に 'abc'(正確に 'abc')の連続数のパーセンテージを示すプログラムを書く必要があります。入力#ABCの#のABBの$のために

、半分は入力#ABCの#のABCの$のために 'ABC'

あるのでbacauseすべての出力1.00を印刷する必要があり、出力0.50を印刷する必要があります:いくつかの例を与えます'abc'

入力#abc#abcghghg $は、出力0を出力する必要があります。入力#ABCの#abcの番号のnnnabcj $に対する

50、出力ここでは0.67

を印刷する必要がありますですexempleについては、単語がABCで始まるが、終わりがないときに私のコードは、それが正常に動作しますが、失敗しましたそれは「ABC」がある場合、コードは毎回成功を増加させるためである0.50

#include <stdio.h> 

int main() 
{ 
    char n1 = 0; 
    char n2 = 0; 
    char n3 = 0; 
    char n4 =0;//Added 
    char test = 0; 
    int success = 0; 
    int total = 0; 
    double result = 0;//changed from int to double 
    printf("Please enter word to check\n");//Added 
    while ((test = getchar()) != '$') 
    { 
     printf("check %c:\n", test);//Only for debug 
     if (test == '#') 
     { 
     n1 = 0; 
     n2 = 0; 
     n3 = 0; 
     total++; 
     } 
      else 
      { 
       n1 = n2; 
       n2 = n3; 
       n3 = test; 

      } 
      if (n1 == 'a' && n2 == 'b' && n3 == 'c') 
      success++; 
    } 
      result = (double)success/total;//casted to double 
      printf("%.2f", result);//changed to %.2f instead of %d, 2 digit only after decimal point 
    return 0; 
} 

答えて

1

を印刷するinstad「$ abcfghgf#のABCの#」入力のための1.00を出力します。 試用版:

#include <stdio.h> 

int main() 
{ 
    char n1 = 0; 
    char n2 = 0; 
    char n3 = 0; 
    char n4 =0;//Added 
    char test = 0; 
    int success = 0; 
    int total = 0; 
    int count = 3; 
    double result = 0;//changed from int to double 
    printf("Please enter word to check\n");//Added 
    while (1) 
    { 
     test = getchar(); //take this out 
     if(test == '$'){ 
      if (n1 == 'a' && n2 == 'b' && n3 == 'c' && count == 3)success++; //check if there is another seq before exit 
      break; 
     } 
     printf("check %c:\n", test);//Only for debug 
     if (test == '#') 
     { 
      if (n1 == 'a' && n2 == 'b' && n3 == 'c' && count == 3) success++; 
      n1 = 0; 
      n2 = 0; 
      n3 = 0; 
      count = 0; 
      total++; 
     }else 
      { 
       n1 = n2; 
       n2 = n3; 
       n3 = test; 
       count++; 
      } 

    } 
    result = (double)success/total;//casted to double 
    printf("%.2f", result);//changed to %.2f instead of %d, 2 digit only after decimal point 
    return 0; 
}