2017-08-07 34 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 –

相關問題