我正在尝试获取输入数学表达式的x因子,但它似乎有些错误。这是我的代码:
#include<iostream>
#include<math.h>
using namespace std;
int main(){
char a[100];
int res = 0; // final answer
int temp = 0; // factor of the x we are focused on - temporarily
int pn = 0; // power of 10 - used for converting digits to number
int conv; // used for conversion of characters to int
cout<< "Enter a: ";
cin>> a; //input expression
for(int i=0; i<100; i++){
// checking if the character is x - then get the factor
if(a[i]=='x'){
for(int j=1; j<=i+1; j++){
conv = a[i-j] - '0'; // conversion
if(conv>=0 && conv<=9){ // check if the character is a number
temp = temp + conv*pow(10, pn); // temporary factor - using power of 10 to convert digit to number
pn++; // increasing the power
}
else{
if(a[i-j]=='-'){
temp = -temp; // check if the sign is - or +
}
break;
}
if(i-j==0){
break;
}
}
res = res+temp; // adding the x factor to other ones
pn = 0;
temp = 0;
}
}
cout<< res;
return 0;
}
它不适用于某些输入,例如:100x + 3x给出102和3x + 3997x-4000x给出-1
但适用于130x和150x!
我的代码有问题,还是有更简单的方法可以做到这一点?
我认为你没有解析+。可能还有一些我在原始代码中看不到的其他问题,可能不是。这是X档案:
int main(){
char a[100];
int res(0);
cout << "Enter a: ";
cin >> a;
for(int i = 0; i < 100; i++){
if(a[i] == 'x'){
int temp(0);
int pn(0);
for(int j = 1; j <= i; j++){
int conv = a[i - j] - '0';
if(conv >= 0 && conv <= 9){
temp += conv*pow(10, pn);
pn++;
} else if(a[i - j] == '-') {
temp = -temp;
break;
} else if(a[i - j] == '+') {
break;
} else {
// what to do...
}
}
res += temp;
}
}
cout << res;
return 0;
}