Why c# compiler not reading the 0 before any digit?
int n;
int[] ar = new int[50];
Console.Write("Enter the size of array= ");
n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
ar[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < n; i++)
{
Console.WriteLine("AR["+i+"]="+ar[i]);
}
Console.Read();
As here you can see that when m entering the 09 or 08 its going to remove it and print the 9 and 8. And when same run on the c++ compiler then its print the 0 and 9 on different indices, why the compilers of both language doing behave lik开发者_开发技巧e this? Why they do not reading it one digit?
The behavior of int.Parse(..) and other string to numeric parsing functions is to strip out any leading characters (zeros in this case) which are irrelevant to the numeric value.
If you wish to keep the leading zero then change the data type of your array to string.
Now that you've posted some code, here's a few suggestions (comments inline)
int n;
bool validNumber;
do {
validNumber = true;
Console.Write("Enter the size of array:");
if(!int.TryParse(Console.ReadLine(), out n)) // use TryParse instead of Parse to avoid formatting exceptions
{
Console.WriteLine("Not a number, please try again");
validNumber = false;
}
} while(!validNumber); // re-prompt if an invalid number has been entered
int[] ar = new int[n]; // declare the array after the size is entered - your code will break if the user enters a number greater than 50
// change to "string[] ar = new string[n];" if you want to keep the full value entered
for (int i = 0; i < n; i++)
{
bool valid;
do {
valid = true;
int num;
string value = Console.ReadLine();
if(int.TryParse(value, out num)) // again - use tryparse.
ar[i] = num; // change to "ar[i] = value;" if you're using a string array.
else {
Console.WriteLine("Please enter that again - not a number");
valid = false;
}
} while(!valid);
}
for (int i = 0; i < n; i++)
{
Console.WriteLine("AR["+i+"]="+ar[i]);
}
Console.Read();
Your array is storing integers, and since 01 and 1 have the same number value, we don't distinguish them.
You'll want to save them as strings, if you need to keep the prefix zeros.
An integer is an integer, not a string.
So 09 is the same as 9, is the same as 000000009. They are all internally represented by the bit pattern 00000101 00000000 00000000 00000000 (at least on x86).
i think its better if you convert your array to string array and then perfrom the operation. Since when it comes to integer 09 and 9 has no difference the numeric values is what that matters. but when its a string its different so use string array to do the operation and if u have to just want to display it then string is better anyways. if u want integer then convert it into int, there are API available.
Console.Read*Line*() is different from cin>> . so
精彩评论