Home > Back-end > The scanf format characters for the % f, but input as symbolic time-varying infinite loop
The scanf format characters for the % f, but input as symbolic time-varying infinite loop
Time:10-22
Procedure is as follows, to achieve a simple arithmetic, when normal input formula, function normally; But when a mistake on purpose, such as input///or @ # $, it becomes infinite loop, the scanf don't Work, a great god answer.
# include & lt; Stdio. H>
Int main () { Double d1, d2, d3, Unsigned char op, noError=1;
While (1) { Printf (" please enter a formula, such as 3 + 2: "); Lf scanf_s (" % % c % lf ", & amp; D1, & amp; Op, & amp; D2);
The switch (op) { Case: '+' d3=d1 + d2; break; Case '-' : d3=d1, d2, break; Case: '*' d3=* d1 d2; break; Case '/' : if (d2!=0) D3=d1/d2. The else { Printf (" divisor cannot be zero!" ); NoError=0; } break; Default: printf (" input error, please input again!" ); NoError=0; } If (noError) Printf (" % 5.2 f % c % 5.2 f=% 5.2 f \ n ", d1, op, d2 and d3). NoError=1; //d1 d2==0; //op='+'; }
The lack of a parameter, because % c need to specify the memory size;
Need to pay attention to input format, because the middle is % c, so there can be only one character between d1 and d2, spare one character at a time the results are different, recommended in scanf_s print one day of the following statements to d1, op, compare d2 type and your input
CodePudding user response:
# include & lt; Stdio. H>
Int main () { Double d1, d2, d3, Unsigned char op, noError;
While (1) { Printf (" please enter a formula, such as 3 + 2 (ctrl-c exit) : "); The rewind (stdin); Lf the if (3==scanf_s (" % % c % lf ", & amp; D1, & amp; Op, & amp; D2)) { NoError=1; The switch (op) { Case: '+' d3=d1 + d2; break; Case '-' : d3=d1, d2, break; Case: '*' d3=* d1 d2; break; Case '/' : If (d2!=0) { D3=d1/d2. } else { Printf (" divisor cannot be zero! \n"); NoError=0; } break; Default: Printf (" input error, please input again! \n"); NoError=0; } If (noError) printf (" % 5.2 lf % c % 5.2 lf=% 5.2 lf \ n ", d1, op, d2 and d3). } else { Printf (" input error, please input again! \n"); } }