由于培训原因,我想编写一个小计算器。为什么要计算10-6 = 16而不是10-6 = 4?
我得到了错误:
Assertion Failed!
Expression: calc("10-6") == 4 && "could not do substraction"
Run Code Online (Sandbox Code Playgroud)
这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <ctype.h>
double calc(char * input);
double extract_first_integer(char * input);
double extract_last_integer(char * input);
char extract_operand(char * input);
int main()
{
assert(calc("10-6") == 4 && "could not do substraction");
return 0;
}
double calc(char * input){
double num1 = extract_first_integer(input);
double num2 = extract_last_integer(input);
char operand = extract_operand(input);
printf("operand is %c\n", operand);
switch (operand)
{
case '-':
printf("num1 - num2: %f\n", num1-num2); // output: 16 instead of 4
return num1 - num2;
break;
}
}
double extract_first_integer(char * input){
char *str = input, *p = str;
double val;
while (*p) { // While there are more characters to process...
if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
// Found a number
val = strtol(p, &p, 10); // Read number
return val;
} else {
// Otherwise, move on to the next character.
p++;
}
}
}
double extract_last_integer(char * input){
char *str = input, *p = str;
double val;
while (*p) { // While there are more characters to process...
if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
// Found a number
val = strtol(p, &p, 10); // Read number
} else {
// Otherwise, move on to the next character.
p++;
}
}
return val;
}
char extract_operand(char * input){
if (strstr(input, "-")) return '-';
}
Run Code Online (Sandbox Code Playgroud)
在extract_last_integer()你里面
while (*p) { // While there are more characters to process...
if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
// Found a number
val = strtol(p, &p, 10); // Read number
} else {
// Otherwise, move on to the next character.
p++;
}
}
Run Code Online (Sandbox Code Playgroud)
递增,p直到遇到第一个数字或-/ +后跟一个数字。因此它将与第一个10数字匹配。不过请注意,您并没有像早return val;于那样打破循环extract_first_integer()。当您继续匹配下一位数字时-6,"10-6"将匹配输入。而且10 - (-6)显然是16
您还可能具有未定义的行为
strtol。该变量str未使用,应str_end改为在参数中传递const char*("10-6")传递给期望的函数char*