I have an issue with converting numbers to words - c#

so i'm having an issue with the decimal part where the number that you input in the console is for example 0,02 and it gives in words only 2 out of the 3 characters (skips the second 0) i tried many solutions including just doing an if() where i have a double mn = 0.9 but i found out that the if works only to 0 it accepts the variable that i made but its seems like it doesnt understands it. If you have any idea how i can fix this glad to hear
P.S I've attached the whole code on the other paragraph. Thank you!
what i want to happen Input 0,02 ---> output zero point zero two
what is happening Input - 0,02 ----> output zero point 2
static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
// OT VIKTOR BOTKOV 304sr
try
{
Console.WriteLine("Въведете число.....:");
string number = Console.ReadLine();
number = ConvertAmount(double.Parse(number));
Console.WriteLine("Числото изписано в думи е : \n{0}", number);
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static String[] units = { "нула", "едно", "две", "три",
"четири", "пет", "шест", "седем", "осем", "девет", "десет", "единайсет",
"дванайсет", "тринайсет", "четиринайсет", "петнайсет", "шеснайсет",
"седемнайсет", "осемнайсет", "деветнайсет" };
private static String[] tens = { "", "", "двайсет", "трийсет", "четиресет",
"педесет", "шейсет", "седемдесет", "осемдесет", "деведесет" };
private static String[] hundreds = {"","сто", "двеста", "триста","четиристотин",
"петстотин", "шестстотин", "седемстотин", "осемстотин", "деветстотин" };
private static String[] thousands = {"","хиляда","две хиялди", "три хиляди","четири хиляди",
"пет хиляди", "шест хиляди", "седем хиляди", "осем хиляди", "девет хиляди" };
private static String[] unitsс = { "нула ", "един", "два", };
public static String ConvertAmount(double amount)
{
try
{
double mn = 0.09;
Int64 amount_int = (Int64)amount;
Int64 amount_dec = (Int64)Math.Round((Decimal)(amount - (double)(amount_int)) * 100);
if (amount_dec == 0)
{
return Convert(amount_int) + " лв.";
}
else if (amount_int <= mn)
{
return Convert(amount_int) + " Цяло и " + " Нула " + Convert(amount_dec) + " ст.";
}
else
{
return Convert(amount_int) + " лв. и " + Convert(amount_dec) + " ст.";
}
}
catch (Exception e)
{
}
return "";
}
public static String Convert(Int64 i)
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
if (i<=2)
{
return unitsс[i];
}
if (i < 20)
{
return units[i];
}
if (i < 100)
{
return tens[i / 10] + ((i % 10 > 0) ? " и " + Convert(i % 10) : "");
}
if (i < 1000)
{
return hundreds[i / 100] + ((i % 100 > 0) ? " и " + Convert(i % 100) : "");
}
if (i < 100000)
{
return Convert(i / 1000) + " Хиляди "
+ ((i % 1000 > 0) ? " " + Convert(i % 1000) : "");
}
else if (i < 1000000)
{
return Convert(i / 10000) + " Хиляди "
+ ((i % 10000 > 0) ? " и " + Convert(i % 10000) : "");
}
if (i < 10000000)
{
return Convert(i / 1000000) + " Милиона "
+ ((i % 1000000 > 0) ? " " + Convert(i % 1000000) : "");
}
if (i < 100000000)
{
return Convert(i / 1000000) + " Милиона "
+ ((i % 1000000 > 0) ? " и " + Convert(i % 1000000) : "");
}
if (i < 1000000000)
{
return Convert(i / 1000000) + " Милиона "
+ ((i % 1000000 > 0) ? " " + Convert(i % 1000000) : "");
}
if (i < 10000000000)
{
return Convert(i / 1000000000) + " Милиaрда "
+ ((i % 1000000000 > 0) ? " " + Convert(i % 1000000000) : "");
}
return Convert(i / 1000000000000) + " "
+ ((i % 1000000000000 > 0) ? " " + Convert(i % 10000000000000) : "");
}
}

Related

Trying to make a Prime Number Checker And Came across issues

I'm new to coding on C# and thought I should try to make a Prime number checker, where you would input a number and it would be checked to see if it was prime or not. I wanted to try and use functions but came across some issues and I am a bit confused. Also, I believe my logic is also wrong but I'm not sure how to fix it. Here is my code any help is appreciated, also could you explain each part of your logic if you fix it:
internal class Program
{
static void Main(string[] args)
{
int number = Convert.ToInt32(Console.ReadLine());
IsNumberPrime();
Console.ReadKey();
}
static int IsNumberPrime(int number)
{
if (number <= 0)
{
Console.WriteLine(number + " is " + "not Prime");
}
else if (number == 1)
{
Console.WriteLine(number + " is " + "not Prime");
}
else if (number > 1)
{
for (int a = 2; number % a == 0; a++)
{
if (number % a == 0)
{
Console.WriteLine(number + " is " + "not Prime");
}
else
{
Console.WriteLine(number + " is " + " Prime");
}
}
}
}
}
There are several issues in your code, it's completely wrong.
first I will focus on the logical problems in your code.
you are not using the return value, so you can change the return type to void.
you should pass number as a parameter to the method IsNumberPrime.
you should modify the condition in the for a loop.
you should move the Console.WriteLine(number + " is Prime"); outside the for loop.
static void IsNumberPrime(int number)
{
if (number <= 0)
{
Console.WriteLine(number + " is not Prime");
}
else if (number == 1)
{
Console.WriteLine(number + " is not Prime");
}
else if (number > 1)
{
for (int a = 2; number > a; a++)
{
if (number % a == 0)
{
Console.WriteLine(number + " is not Prime");
return;
}
}
Console.WriteLine(number + " is Prime");
}
}
Now comes to the performance, you can run the loop till the square root of the number, not till the number, which will improve the performance of the code. also, no need to increment the value of a by 1, you can increment by 2 (first check divide by 2 and then just check divide by the odd numbers, no need to check with the other even numbers).
Here is the optimized code.
static void IsNumberPrime(int number)
{
if (number <= 1)
{
Console.WriteLine(number + " is " + "not Prime");
return;
}
if (number == 2)
{
Console.WriteLine(number + " is " + " Prime");
return;
}
if (number % 2 == 0)
{
Console.WriteLine(number + " is " + "not Prime");
return;
}
for (int i = 3; i <= Math.Sqrt(number); i = i + 2)
{
if (number % i == 0)
{
Console.WriteLine(number + " is " + "not Prime");
return;
}
}
Console.WriteLine(number + " is " + " Prime");
}
My comments will make your solution run, I didn't check the algorithm for Primes. Your Main function is calling IsNumberPrime() function which expects an integer value in its parameter.
Another remark is that the IsNumberPrime returns an integer value. Because you’re logging the results to the console, you should change the return type in the method declaration to void. Below are my adjustments to your code:
static void Main(string[] args)
{
int number = Convert.ToInt32(Console.ReadLine());
IsNumberPrime(number);
Console.ReadKey();
}
static void IsNumberPrime(int number)
{
if (number <= 0)
{
Console.WriteLine(number + " is " + "not Prime");
}
else if (number == 1)
{
Console.WriteLine(number + " is " + "not Prime");
}
else if (number > 1)
{
for (int a = 2; number % a == 0; a++)
{
if (number % a == 0)
{
Console.WriteLine(number + " is " + "not Prime");
}
else
{
Console.WriteLine(number + " is " + " Prime");
}
}
}
}

How to Continue The Text from one textblock to another textblock if the first textblock text length is limited?

I am creating a bank cheques so in that i have 6 textblocks first 2 is for date and name on the cheque 3rd,4th,5th is for amount in words and 6th is for amount in figures so endusers of my organization will provide date,name and amount in figures and amount in figures will be relected and converted in amount in words upto here it is fine but my requirement is in the 3rd overflowing and i would like to continue the text in 4th textblock.
public ICICICHEQUE()
{
InitializeComponent();
if (!this.IsVisible)
{
this.Show();
}
this.WindowState = WindowState.Normal;
this.WindowState = WindowState.Minimized;
this.Activate();
this.Topmost = true;
this.Focus();
this.ShowInTaskbar = true;
if (txtblckAmountInFigures.Text != null)
{
ConvertTxtBlockInDecimal();
}
}
private void ConvertTxtBlockInDecimal()
{
txtblckAmountInWords.Text = UtilityMethods.ConvertToWords(Convert.ToDecimal(txtblckAmountInFigures.Text), "isCheque") + "only/-"+"\r\n";
}
you need to split your code and use these two methods
public static string DecimalToText(string decimalPart)
{
string[] digits = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
string result = "";
foreach(char c in decimalPart)
{
int i = (int)c - 48;
if (i < 0 || i > 9) return ""; // invalid number, don't return anything
result += " " + digits[i];
}
return result;
}
public static string NumberToText(int number, bool useAnd, bool useArab)
{
if (number == 0) return "Zero";
string and = useAnd ? "and " : ""; // deals with using 'and' separator
if (number == -2147483648) return "Minus Two Hundred " + and + "Fourteen Crore Seventy Four Lakh Eighty Three Thousand Six Hundred " + and +"Forty Eight";
int[] num = new int[4];
int first = 0;
int u, h, t;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if (number < 0)
{
sb.Append("Minus ");
number = -number;
}
string[] words0 = {"" ,"One ", "Two ", "Three ", "Four ", "Five " ,"Six ", "Seven ", "Eight ", "Nine "};
string[] words1 = {"Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "};
string[] words2 = {"Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ","Eighty ", "Ninety "};
string[] words3 = { "Thousand ", "Lakh ", "Crore " };
num[0] = number % 1000; // units
num[1] = number / 1000;
num[2] = number / 100000;
num[1] = num[1] - 100 * num[2]; // thousands
num[3] = number / 10000000; // crores
num[2] = num[2] - 100 * num[3]; // lakhs
for (int i = 3; i > 0; i--)
{
if (num[i] != 0)
{
first = i;
break;
}
}
for (int i = first; i >= 0; i--)
{
if (num[i] == 0) continue;
u = num[i] % 10; // ones
t = num[i] / 10;
h = num[i] / 100; // hundreds
t = t - 10 * h; // tens
if (h > 0) sb.Append(words0[h] + "Hundred ");
if (u > 0 || t > 0)
{
if (h > 0 || i < first) sb.Append(and);
if (t == 0)
sb.Append(words0[u]);
else if (t == 1)
sb.Append(words1[u]);
else
sb.Append(words2[t - 2] + words0[u]);
}
if (i != 0) sb.Append(words3[i - 1]);
}
string temp = sb.ToString().TrimEnd();
if (useArab && Math.Abs(number) >= 1000000000)
{
int index = temp.IndexOf("Hundred Crore");
if (index > -1) return temp.Substring(0, index) + "Arab" + temp.Substring(index + 13);
index = temp.IndexOf("Hundred");
return temp.Substring(0, index) + "Arab" + temp.Substring(index + 7);
}
return temp;
}
}
Use substring to split the text and display in 2 textboxes.
var requiredText = UtilityMethods.ConvertToWords(Convert.ToDecimal(txtblckAmountInFigures.Text), "isCheque") + "only/-"+"\r\n";
if(requiredText.Count > 255)
{
textbox1.Text = requiredText.subString(0,255);
textbox2.Text = requiredText.subString(255,requiredText.Count-1);
}
else
{
textbox1.Text = requiredText;
}

Hamming code extension

I have taken the code from this website of Hamming code. If I wanted to implement it on 12 bits of message and 7 bits of Parity what changes do I have to do? I have added till DI[11] and CI[6] bit couldn't get to inter-prate it's logic
string NrBinary;
long pp, Key=8, number;
double x, y;
Console.WriteLine("Give binary value till 12 bit: ");
NrBinary = Console.ReadLine();
if (NrBinary.Length <= 12)
{
if (NrBinary.Length == 1)
NrBinary = "000000000000" + NrBinary;
if (NrBinary.Length == 2)
NrBinary = "00000000000" + NrBinary;
if (NrBinary.Length == 3)
NrBinary = "0000000000" + NrBinary;
if (NrBinary.Length == 4)
NrBinary = "000000000" + NrBinary;
if (NrBinary.Length == 5)
NrBinary = "00000000" + NrBinary;
if (NrBinary.Length == 6)
NrBinary = "0000000" + NrBinary;
if (NrBinary.Length == 7)
NrBinary = "000000" + NrBinary;
if (NrBinary.Length == 8)
NrBinary = "00000" + NrBinary;
if (NrBinary.Length == 9)
NrBinary = "0000" + NrBinary;
if (NrBinary.Length == 10)
NrBinary = "000" + NrBinary;
if (NrBinary.Length == 11)
NrBinary = "00" + NrBinary;
if (NrBinary.Length == 12)
NrBinary = "0" + NrBinary;
pp = NrBinary.Length;
number = Convert.ToInt64(NrBinary);
Console.WriteLine("PP = " + pp);
for (Key = 0; Key < pp; ++Key)
{
x = Math.Pow(2, Key) - 1;
y = pp + Key;
if (x >= y)
{
goto Mess;
}
}
Mess:
Console.WriteLine("Controlled bit needed Key = " + Key + "\n");
long[] parity = new long[pp];
long[] DI = new long[pp];
long[] CI = new long[Key];
DI[0] = number % 10;
DI[1] = (number / 10) % 10;
DI[2] = (number / 100) % 10;
DI[3] = (number / 1000) % 10;
DI[4] = (number / 10000) % 10;
DI[5] = (number / 100000) % 10;
DI[6] = (number / 1000000) % 10;
DI[7] = (number / 10000000) % 10;
DI[8] = (number / 100000000) % 10;
DI[9] = (number / 1000000000) % 10;
DI[10] = (number / 10000000000) % 10;
DI[11] = (number / 100000000000) % 10;
CI[0] = DI[11] ^ DI[0] ^ DI[1];
CI[1] = DI[1] ^ DI[2] ^ DI[3];
CI[2] = DI[3] ^ DI[4] ^ DI[5];
CI[4] = DI[5] ^ DI[6] ^ DI[7];
CI[5] = DI[7] ^ DI[8] ^ Convert.ToInt64(DI[9]);
CI[6] = CI[1] ^ CI[2] ^ CI[3] ^ CI[4] ^ CI[5] ^ CI[6];
Console.WriteLine("\n = " + CI[0] + "" + CI[1] + "" + CI[2] + "" + CI[3] + "" + CI[4] + "" + CI[5] + "" + CI[6] + "\n");
Console.Write("Bit with Hamming code: ");
Console.WriteLine(DI[11] + "" + DI[10] + "" + DI[9] + "" + DI[8] + "" + DI[7] + "" + DI[6] + "" + DI[5] + "" + DI[4] + "" + DI[3]
+ "" + DI[2] + "" + DI[1] + "" + DI[0] + "" + CI[6] + "" + CI[5] + "" + CI[4] + "" + CI[3] + "" + CI[2] + "" + CI[1] + "" + CI[0]);
/*Console.WriteLine(DI[7] + "" + DI[6] + "" + DI[5] + "" + DI[4] + "" + CI[3] + "" + DI[3]
+ "" + DI[2] + "" + DI[1] + "" + CI[2] + "" + DI[0] + "" + CI[1] + "" + CI[0]);*/
}
else
{
Console.WriteLine("\n\n 8 bit character maximally:)");
}
Console.ReadKey();
}

"Object cannnot be cast from DBNull to other types"

I am working on an asp.net project, it takes values from the front end, stores them as string in a matrix. When the matrix size is greater than 5 * 5, it keep returns an InvalidCastException (It works fine on 5 * 5 matrix and under).
The code is attached below, with a screen shot of Exception:
public partial class WebForm1 : System.Web.UI.Page
{
public DataSet relmatrix = new DataSet();
public DataTable rt = new DataTable();
public Double[] inconsistency;
public int nodersnum;
public string strrel;
protected void Button1_Click(object sender, EventArgs e)
{
nodersnum = Convert.ToInt16(count.Text);
switch (nodersnum)
{
case 1:
break;
case 2:
{ strrel = RelationAB2.Text; }
break;
case 3:
{ strrel = RelationAB3.Text + " " + RelationAC3.Text + " " + RelationBC3.Text; }
break;
case 4:
{ strrel = RelationAB4.Text + " " + RelationAC4.Text + " " + RelationAD4.Text + " " + RelationBC4.Text + " " + RelationBD4.Text + " " + RelationCD4.Text; }
break;
case 5:
{ strrel = RelationAB5.Text + " " + RelationAC5.Text + " " + RelationAD5.Text + " " + RelationAE5.Text + " " + RelationBC5.Text + " " + RelationBD5.Text + " " + RelationBE5.Text + " " + RelationCD5.Text + " " + RelationCE5.Text + " " + RelationDE5.Text; }
break;
case 6:
{ strrel = RelationAB6.Text + " " + RelationAC6.Text + " " + RelationAD6.Text + " " + RelationAE6.Text + " " + RelationAF6.Text + " " + RelationBC6.Text + " " + RelationBD6.Text + " " + RelationBE6.Text + " " + RelationBF6.Text + " " + RelationCD6.Text + " " + RelationCE6.Text + " " + RelationCF6.Text + " " + RelationDE6.Text + " " + RelationDF6.Text + " " + RelationEF6.Text; }
break;
case 7:
{ strrel = RelationAB7.Text + " " + RelationAC7.Text + " " + RelationAD7.Text + " " + RelationAE7.Text + " " + RelationAF7.Text + " " + RelationAG7.Text + " " + RelationBC7.Text + " " + RelationBD7.Text + " " + RelationBE7.Text + " " + RelationBF7.Text + " " + RelationBG7.Text + " " + RelationCD7.Text + " " + RelationCE7.Text + " " + RelationCF7.Text + " " + RelationCG7.Text + " " + RelationDE7.Text + " " + RelationDF7.Text + " " + RelationDG7.Text + " " + RelationEF7.Text + " " + RelationEG7.Text + " " + RelationFG7.Text; }
break;
default:
{ strrel = ""; }
break;
}
GenerateTable.generatetable(relmatrix, strrel, rt, nodersnum);
Class1.generatePC(nodersnum, relmatrix);
int num = 0;
double maxincon = 0.0;
int mi = 0, mj = 0, mk = 0;
inconsistency = new Double[43] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (int i = 0; i < nodersnum - 2; i++)
{
for (int k = i + 1; k < nodersnum - 1; k++)
{
for (int j = k + 1; j < nodersnum; j++)
{
if ((Convert.ToString(relmatrix.Tables["relTable"].Rows[i][j]) != " ") && (Convert.ToString(relmatrix.Tables["relTable"].Rows[i][k]) != " ") && (Convert.ToString(relmatrix.Tables["relTable"].Rows[k][j]) != " "))
{
Double a = Convert.ToDouble(relmatrix.Tables["relTable"].Rows[i][j]);//obtain value from the matrix
Double b = Convert.ToDouble(relmatrix.Tables["relTable"].Rows[i][k]);//obtain value from the matrix
//PROBLEM
Double c = Convert.ToDouble(relmatrix.Tables["relTable"].Rows[k][j]);//obtain value from the matrix
inconsistency[num] = (Class1.Min(System.Math.Abs(1 - a / (b * c)), System.Math.Abs(1 - (b * c) / a)));//calculate the inconsistency value and store in the inconsistency array
//Get the biggest inconsistency number
if (inconsistency[num] >= maxincon)
{
maxincon = inconsistency[num];
mi = i;
mj = j;
mk = k;
}
num++;
}
}
}
}
Class1.sort(inconsistency);//sort inconsistency array
while (inconsistency[0] > 0.3333333)
{
for (int i = 0; i < nodersnum - 2; i++)
{
for (int k = i + 1; k < nodersnum - 1; k++)
{
for (int j = k + 1; j < nodersnum; j++)
{
if ((Convert.ToString(relmatrix.Tables["relTable"].Rows[i][j]) != " ") && (Convert.ToString(relmatrix.Tables["relTable"].Rows[i][k]) != " ") && (Convert.ToString(relmatrix.Tables["relTable"].Rows[k][j]) != " "))
{
Double a = Convert.ToDouble(relmatrix.Tables["relTable"].Rows[i][j]);//obtain value from the matrix
Double b = Convert.ToDouble(relmatrix.Tables["relTable"].Rows[i][k]);//obtain value from the matrix
// PROBLEM
Double c = Convert.ToDouble(relmatrix.Tables["relTable"].Rows[k][j]);//obtain value from the matrix
if (inconsistency[0] == (Class1.Min(System.Math.Abs(1 - a / (b * c)), System.Math.Abs(1 - (b * c) / a))))//calculate the inconsistency value and store in the inconsistency array
{
if ((b * c) < a)
{
double A = (b * c) / ((a + b + c) * (a + b + c));
double B = (a + 2 * b * c) / (a + b + c);
double C = b * c - a;
double m = B * B - 4 * A * C;
if (m < 0)
{
Console.Write("error");
break;
}
else
{
double x1 = (-1 * B + System.Math.Sqrt(m)) / (2 * A);
double x2 = (-1 * B - Math.Sqrt(m)) / (2 * A);
if ((x1 > 0) && (x2 < 0))
{
b = (float)(b + (b * x1) / (a + b + c));
c = (float)(c + (c * x1) / (a + b + c));
a = (float)(a - (a * x1) / (a + b + c));
}
else if ((x1 < 0) && (x2 > 0))
{
b = (float)(b + (b * x2) / (a + b + c));
c = (float)(c + (c * x2) / (a + b + c));
a = (float)(a - (a * x2) / (a + b + c));
}
else if ((x1 > 0) && (x2 > 0))
{
double x = Class1.Min((float)x1, (float)x2);
b = (float)(b + (b * x) / (a + b + c));
c = (float)(c + (c * x) / (a + b + c));
a = (float)(a - (a * x) / (a + b + c));
}
else if ((x1 < 0) && (x2 < 0))
{
break;
}
}
}
else if ((b * c) > a)
{
double A = (b * c) / ((a + b + c) * (a + b + c));
double B = -1 * (a + 2 * b * c) / (a + b + c);
double C = b * c - a;
double m = B * B - 4 * A * C;
if (m < 0)
{
Console.Write("error");
break;
}
else
{
double x1 = (-1 * B + Math.Sqrt(m)) / (2 * A);
double x2 = (-1 * B - Math.Sqrt(m)) / (2 * A);
if ((x1 > 0) && (x2 < 0))
{
b = (float)(b - (b * x1) / (a + b + c));
c = (float)(c - (c * x1) / (a + b + c));
a = (float)(a + (a * x1) / (a + b + c));
}
else if ((x1 < 0) && (x2 > 0))
{
b = (float)(b - (b * x2) / (a + b + c));
c = (float)(c - (c * x2) / (a + b + c));
a = (float)(a + (a * x2) / (a + b + c));
}
else if ((x1 > 0) && (x2 > 0))
{
double x = Class1.Min((float)x1, (float)x2);
b = (float)(b - (b * x) / (a + b + c));
c = (float)(c - (c * x) / (a + b + c));
a = (float)(a + (a * x) / (a + b + c));
}
else if ((x1 < 0) && (x2 < 0))
{
break;
}
}
}
}
relmatrix.Tables["relTable"].Rows[i][j] = Convert.ToString(a);
relmatrix.Tables["relTable"].Rows[i][k] = Convert.ToString(b);
relmatrix.Tables["relTable"].Rows[k][j] = Convert.ToString(c);
}
}
}
}
num = 0;
maxincon = 0.0;
mi = 0;
mj = 0;
mk = 0;
for (int i = 0; i < nodersnum - 2; i++)
{
for (int k = i + 1; k < nodersnum - 1; k++)
{
for (int j = k + 1; j < nodersnum; j++)
{
if ((Convert.ToString(relmatrix.Tables["relTable"].Rows[i][j]) != " ") && (Convert.ToString(relmatrix.Tables["relTable"].Rows[i][k]) != " ") && (Convert.ToString(relmatrix.Tables["relTable"].Rows[k][j]) != " "))
{
Double a = Convert.ToDouble(relmatrix.Tables["relTable"].Rows[i][j]);//obtain value from the matrix
Double b = Convert.ToDouble(relmatrix.Tables["relTable"].Rows[i][k]);//obtain value from the matrix
Double c = Convert.ToDouble(relmatrix.Tables["relTable"].Rows[k][j]);//obtain value from the matrix
inconsistency[num] = (Class1.Min(System.Math.Abs(1 - a / (b * c)), System.Math.Abs(1 - (b * c) / a)));//calculate the inconsistency value and store in the inconsistency array
// Get the biggest inconsistency number
if (inconsistency[num] >= maxincon)
{
maxincon = inconsistency[num];
mi = i;
mj = j;
mk = k;
}
num++;
}
}
}
}
//sort inconsistency array
Class1.sort(inconsistency);
}
//Fill up the whole pairwise comparsion matrix, when row=col, the value =1, when row<col the vaule[col][row] is "1/"[col][row]
//nodersnum is how many nodes, row is the matrix row, col is column of matrix
for (int row = 0; row < nodersnum; row++)
{
for (int col = row; col < nodersnum; col++)
{
if (row < col)
{
//set the the value of lower matrix
relmatrix.Tables["relTable"].Rows[col][row] = "1/" + relmatrix.Tables["relTable"].Rows[row][col];
}
//set the value of diagnoal
else if (row == col)
{
relmatrix.Tables["relTable"].Rows[row][col] = "1";
}
}
}
//compute the weight of each element
Double[] rowproduct;
rowproduct = new Double[7] { 1, 1, 1, 1, 1, 1, 1 };
for (int i = 0; i < nodersnum; i++)
{
for (int j = 0; j < nodersnum; j++)
{
if (i >= j)
{
rowproduct[i] = rowproduct[i] / Convert.ToDouble(relmatrix.Tables["relTable"].Rows[j][i]);
}
else
{
rowproduct[i] = rowproduct[i] * Convert.ToDouble(relmatrix.Tables["relTable"].Rows[i][j]);
}
}
}
Double[] num1;
num1 = new Double[7] { 0, 0, 0, 0, 0, 0, 0 };
double numsum = 0;
//compute each row total number(power of node number)
for (int i = 0; i < nodersnum; i++)
{
num1[i] = Math.Pow(rowproduct[i], 1 / (double)nodersnum);
numsum = numsum + num1[i];
}
//transfer into the number of percentage
Double[] weight;
weight = new Double[7] { 0, 0, 0, 0, 0, 0, 0 };
for (int i = 0; i < nodersnum; i++)
{
weight[i] = (int)Math.Round(100 * num1[i] / numsum * 100) / 100f;
Console.WriteLine(weight[i]);
}
GridView2.DataSource = relmatrix;
GridView2.DataBind();
this.GridView2.Rows[mi].Cells[mj].BackColor = System.Drawing.Color.Red;
this.GridView2.Rows[mi].Cells[mk].BackColor = System.Drawing.Color.Red;
this.GridView2.Rows[mk].Cells[mj].BackColor = System.Drawing.Color.Red;
Label3.Text = "Maximum Inconsistency after Reduction: " + Convert.ToString(inconsistency[0]);
TextBox1.Text = Convert.ToString(weight[0]);
TextBox2.Text = Convert.ToString(weight[1]);
TextBox3.Text = Convert.ToString(weight[2]);
TextBox4.Text = Convert.ToString(weight[3]);
TextBox5.Text = Convert.ToString(weight[4]);
TextBox6.Text = Convert.ToString(weight[5]);
TextBox7.Text = Convert.ToString(weight[6]);
}
}
Looks like your matrix contains null values. You cannot cast them into Double.
Check like this:
if (relmatrix.Tables["relTable"].Rows[i][k] != DBNull.Value)
Or
if (relmatrix.Tables["relTable"].Rows[i][k] != null)
Use nullable double as shown below:
var mynull = DBNull.Value;
Double? c = Convert.IsDBNull(mynull) ? (double?)null : Convert.ToDouble(mynull);
In your case:
Double? c = Convert.IsDBNull(relmatrix.tables["relTable"].Rows[k][j]) ? (double?)null : Convert.ToDouble(relmatrix.tables["relTable"].Rows[k][j]);;
Alternatively using if-else:
if(Convert.IsDBNull(relmatrix.tables["relTable"].Rows[k][j]) == true)
{
Double? c = (double?)null;
}
else
{
Double? c = Convert.ToDouble(relmatrix.tables["relTable"].Rows[k][j]);
}

Numbers to words using arrays

I am trying to make a simple number to english words program and I've decided to use arrays. However whenever I enter a number greater than 99, I get an error in the third if clause.. What do I need to change to fix that? Here's my code;
class Program
{
static void Main(string[] args)
{
string[] uptonineteen = {"Zero","One","Two","Three","Four",
"Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen","Fourteen","Fifteen",
"Sixteen","Seventeen","Eighteen","Nineteen"};
string[] ten = {"","","Twenty","Thirty","Forty","Fifty",
"Sixty","Seventy","Eighty","Ninety",};
Console.WriteLine(" ---------------");
int i = int.Parse(Console.ReadLine());
if (i < 20)
{
Console.WriteLine(uptonineteen[i]);
}
if (i < 100)
{
Console.WriteLine(ten[i / 10] + ((i % 10 > 0) ? "" + uptonineteen[i%10] : ""));
}
if (i <= 999)
{
object lenthree = ten[i / 100] + "hundred"+" " + ((i % 100 > 0) ? "and" +" "+ uptonineteen[i % 1000] : "");
Console.WriteLine(lenthree);
}
Console.ReadKey();
}
}
}
Try this...
class Program
{
static void Main(string[] args)
{
string[] uptonineteen = {"Zero","One","Two","Three","Four",
"Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen","Fourteen","Fifteen",
"Sixteen","Seventeen","Eighteen","Nineteen"};
string[] ten = {"", "","Twenty","Thirty","Forty","Fifty",
"Sixty","Seventy","Eighty","Ninety",};
Console.WriteLine(" ---------------");
int i = int.Parse(Console.ReadLine());
if (i < 20)
{
Console.WriteLine(uptonineteen[i]);
}
else if (i < 100)
{
Console.WriteLine(((((i % 100) / 10) > 1) ? ten[((i % 100) / 10)] + ((i % 10) > 0 ? " " + uptonineteen[(i % 10)] : "") : " and " + uptonineteen[i % 100]));
}
else if (i <= 999)
{
object lenthree = uptonineteen[(i % 1000) / 100] + " hundred " + ((((i % 100) / 10) > 1) ? ten[((i % 100) / 10)] + ((i % 10) > 0 ? " " + uptonineteen[(i % 10)] : "") : " and " + uptonineteen[i % 100]);
Console.WriteLine(lenthree);
}
Console.ReadLine();
}
}
I've seen this too many times... This one handles, such as doing check writing and you may need to go into millions, thousands and includes cents at the end...
public class NumToWords
{
public NumToWords()
{}
string[] OneToNineteen =
{ "zero",
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
// empty string for zero-place-holder for tens grouping
string[] Tens = { "", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
// leave blank for "hundreds" because you would NOT do 123 as One hundred twenty-three hundred.
string[] Block3Section = { "", "thousand", "million", "billion" };
public string ToEnglish(int num)
{
int Block3Seq = 0;
int curSegment;
int tmp;
string FinalWords = "";
string curWord = "";
while (num > 0)
{
curSegment = num % 1000; // get only 3 digits worth (right) of the number
num = (num - curSegment) / 1000; // subtract this portion from the value
if (curSegment > 0)
{
// always add the closing word as we HAVE something to build out
curWord = "";
// how many "hundreds" of the current segment
tmp = (int)curSegment / 100;
if (tmp > 0)
curWord += " " + OneToNineteen[tmp] + " hundred";
// what is remainder of this 100 based segment
tmp = curSegment % 100;
if (tmp < 20)
curWord += " " + OneToNineteen[tmp];
else
{
curWord += " " + Tens[(int)tmp / 10]
+ '-' + OneToNineteen[tmp % 10];
}
// always add the closing word as we HAVE something to build out
curWord += " " + Block3Section[Block3Seq];
// add the section above to the overall words
FinalWords = curWord + FinalWords;
}
// to allow the next closing word for segment such as thousand, million, billion, etc
Block3Seq++;
}
return FinalWords;
}
}
string lenthree = ten[i / 100] + "hundred" + " " +
((i % 100 > 0) ? "and" + " " + uptonineteen[i % 100] : "");
The last 1000 should be 100. But since your uptonineteen isn't full, you still can't enter full numbers correctly.
After handling a case number > x you should continue with the remainder number = number % x or number %= x which is the same. Also you should really make the distinction between getting the English text and doing tests on the console. Console.WriteLines and Console.ReadKeys should not appear withing the logic. Build the English string using a StringBuilder by using this general structure:
public static string ToEnglish(int number)
{
var sb = new StringBuilder();
if (number >= 100) {
...
number %= 100;
}
if (sb.Length > 0 && number != 0) {
sb.Append("and ");
}
if (number >= 20) {
...
number %= 10;
}
if (sb.Length == 0 || number != 0) {
...
}
return sb.ToString();
}
Note: I don't post a complete solution since I assume its homework.
The console test looks like this
while (true) {
Console.Write("Please enter a number or `q` to quit: ");
string s = Console.ReadLine();
if (s == "q") {
break;
}
int i = int.Parse(s);
Console.WriteLine(ToEnglish(i));
}
string[] ones = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirtheen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen","nineteen", "twenty" };
string[] tens = { "Ten", "Twenty", "Thirthy", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
Console.WriteLine("Enter a number");
int i = int.Parse(Console.ReadLine());
if (i < 20)
{
Console.WriteLine(ones[i]);
}
if (i > 30 & i < 100)
{
Console.WriteLine(tens[((i%100)/10)-1]+ " " + ones[(i % 10)]);
}
if (i > 100 & i < 1000)
{
if (((i % 100) % 10) == 0)
{
Console.WriteLine(ones[(i / 100)] + " hundred " + tens[((i % 100) / 10) - 1]);
}
else
{
Console.WriteLine(ones[(i / 100)] + " hundred " + tens[((i % 100) / 10) - 1] + " and " + ones[((i % 100) % 10)]);
}
}
Console.ReadLine();

Categories