2017-08-07 69 views
-3

我想使用数学克拉默定理做一个确定性计算器,正如你所看到的,我将该定理转化为代码convertedString = Convert.ToString (x * y1 * 1 + x1 * y2 * 1 + x2 * x * y - (1 * y1 * x2 + 1 * y2 * y + 1 * y * x1));所有的好东西,直到我需要计算2个未知数的时候,我不知道如何在代码中告诉“x + x = 2x”或“3y-y = 2y”,所以我认为如果将Crammer方程转换为字符串,我可以找到所有匹配,如x + xy + 2yy * y,并从该解决方案开始解决我的初始问题,就像我找到x * x模式一样,我会通过if语句或者x * x模式为x^2的东西来告诉PC。 所以说,我想找出一些特定的序列,如X * yy + x存在于一个字符串中,我尝试了一些foreach循环和for循环,但我不能让它工作,我不知道我应该如何接下来的问题,寻求帮助。我应该如何通过字符串搜索字符序列,如“x * y”?

这里是我的代码:

using System; 
using InputMath; 

namespace MathWizard 
{ 
    class Determinants 
    { 
     //Determinant of a first point and a second graphical point on the xoy axis. 
     public static void BasicDeterminant() 
     { 
      float x; 
      float y; 
      float x1 = Input.x1; 
      float y1 = Input.y1; 
      float x2 = Input.x2; 
      float y2 = Input.y2; 
      float result; 
      string convertedString; 
      string pointsValue; 
      string[] point; 

      Console.WriteLine("Please introduce the 2 graphical points (A and B) \n in the order x1 y1 x2 y2, separated by a space "); 

      pointsValue = Console.ReadLine(); 
      point = pointsValue.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 


      x1 = Convert.ToInt32(point[0]); 
      y1 = Convert.ToInt32(point[1]); 
      x2 = Convert.ToInt32(point[2]); 
      y2 = Convert.ToInt32(point[3]); 


      //The Cramer's Rule for solving a 2 points determinant (P1(x1,y1) and P2(x2,y2) 
      convertedString = Convert.ToString (x * y1 * 1 + x1 * y2 * 1 + x2 * x * y - (1 * y1 * x2 + 1 * y2 * y + 1 * y * x1)); 

     } 
    } 
} 
+0

你声明'x1,x2,y1,y2'为'float',但是然后使用'Convert.ToInt16'从输入中获取它们。哪种类型是正确的? –

+2

此代码不包含有关查找字符串的任何内容。你想达到什么目的? – PhilMasterG

+0

您是否复制/粘贴其他人的代码,然后尝试修改它?这个不成立。 'x'和'y'总是'1',你也有一些硬编码的'1',全部用于乘法。 –

回答

0
bool found = false; 
int xyCount = 0; 

if(convertedString.Contains("X*Y")){ 
    found = true; 
     xyCount++; 
     //makes a substring without the first case of the "X*Y" 
     string s = convertedString.SubString(convertedString.IndexOf("X*Y")) 
     if(s.Contains("X*Y")){ 
     xyCount++; 
    } 

它可能不会做到这一点的最好办法,但你可能可以做一个更好的方法做这样

+0

我可以使用此解决方案从字符串中查找每个模式吗?即使它是一样的?谢谢你的回答tho :)。 – Noobie

+0

这只会发现一次,要多次找到它,您将不得不使用.indexof。我将编辑我的答案 – jdwee

0

东西,你也可以使用以下regex其中每个运营商都会发现x * y不区分大小写:

string pattern = /(x(\*|\+|\-|\/|\^)y)/gi; 

然后你可以做一些string.Contains(pattern);检查。让我知道这是否有帮助。

编辑:更新的模式

更新的模式,以便它也将允许变量,例如y9X10。任何单个字符(x或y)后跟任意数量的数字。

string pattern =/(x\d*(\*|\+|\-|\/|\^)y\d*)/gi; // could match X1*y9 

这并不占空格,所以你可以使用一些.replace()摆脱空白的,或者使用.split(/\s/)并用该图案之前没有拿到空白的字符串数组。

+0

您能否向我的鳕鱼展示您的解决方案的实施情况,我不明白该如何实施它...谢谢! – Noobie

+0

那么对我来说还是有困惑。我不确定为什么你的变量以'floats'开始,然后转换为'int',然后将它转换为'toString()'。当我第一次读到这个时,它只会要求找到任何序列'x * Y'。现在你想让你的代码添加未知数? @Noobie –