2017-03-16 184 views
1

你好我需要一些帮助我的程序的这一部分是得到一个输入字符串像2x³+2y²并将它分为2个数组termos = terms和exp = exponential,但我似乎无法让它工作比较字符串与变量类型

#include <stdio.h> 
#include <math.h> 

int main() 
{ 
    char poly[50]; 
    int termos[10]; 
    int exp[10]; 
    int contt=0, conte=0, i=0; 
    char var1, var2, var3; 

    printf("Introduza o polinómio\n"); 
    scanf("%s", &poly); 

    for(i=0; i<50; i++) 
    { 
    if(poly[i-1]==char && poly[i]==int && poly[i-1]!='+') 
    { 
     exp[conte]=poly[i]; 
     conte++; 
    } 

    if(poly[i]==int) 
    { 
     termos[contt]=poly[i]; 
     contt++; 
    } 

    if(poly[i]=='x') 
     var1=poly[i]; 
    if(poly[i]=='y') 
     var2=poly[i]; 
    if(poly[i]=='z') 
     var3=poly[i]; 
    } 
+1

请查看您的for循环中的索引。从i = 0开始,尝试检索[i - 1]是不正确的。 – AlexG

+0

代码可能不应循环到数组的末尾,而是字符串的结尾:for(i = 0; i <50; i ++)' - >'for(i = 0; poly [i]; i ++ )对于(i = 0; i <50; i ++),' – chux

+0

'不正确,因为输入字符串可能更短。使用:'我= 0; while(poly [i]!='\ 0'){... i ++;}' –

回答

0

根本不可能,中没有运行时类型信息。也许你应该阅读The XY Problem并在稍后再提问。

0

if(poly[i-1]==char && poly[i]==int && poly[i-1]!='+') 

你想知道poly[i-1]为英文字母的线,例如一个'a',或者是一个数字。您可以使用ctype.h中的以下函数:

// among the includes 
#include <ctype.h> 

// later 
if(isalpha(poly[i-1]) && isdigit(poly[i]) && poly[i-1]!='+') 

代码中存在更多问题。我们将发布这些评论。

+0

就像将保存到'exp []'改成'exp [conte] = poly [i] - '0'; //从ASCII数字转换为数字' – infixed

+0

btw,使用'exp []'可能是一个令人困惑的名字,因为'exp(n)'是一个常用的反对数函数 – infixed