簡體   English   中英

C ++-查找數學表達式的x因子

[英]C++ - Finding x Factor of a math expression

我正在嘗試獲取輸入數學表達式的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

但是適用於130倍和150倍!

我的代碼是否有問題,或者有更簡單的方法做到這一點?

我認為您不是在解析+。 我可能在原始代碼中看不到其他問題,也許不是。 這是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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM