I have a problem on replacing the value as I'm not sure which function to use or how to use it.
The question: Create and populate an array of 5 doubles. Ask the user to input a value 'v' and an index 'i'. Your program should replace the value at index 'i' in the array with the value 'v' while shifting each element to the right and dropping the last element.
This is what I've done so far but it hasn't worked
double[] myDoubleArray = {1, 2, 3, 4, 5};
System.Console.Write(" Please input a value: ");
int v = Convert.ToInt32(Console.ReadLine());
System.Console.Write(" Please input an index value: ");
int i = Convert.ToInt32(Console.ReadLine());
myDoubleArray[i] = v;
You are explicitly saying that this is an assignment (which, in my mind, is OK, as long as you say so). However, I don't like doing your assignments; if I do it, you won't learn anything. Instead, I'm going to help you figure it out. First your code:
double[] myDoubleArray = {1, 2, 3, 4, 5};
System.Console.Write(" Please input a value: ");
int v = Convert.ToInt32(Console.ReadLine());
System.Console.Write(" Please input an index value: ");
int i = Convert.ToInt32(Console.ReadLine());
myDoubleArray[i] = v;
Now the assignment, more explicitly:
You have done the first two parts.
What you need to do is do swap the last two pieces - first make room for the new element, and then, once there is a place for the new value, put it in.
To make room for the new value, you have two cases:
i
th entry to the i+1
th entry. While you are doing this, you will likely find out why most programmers think that "off-by-one" issues are the most common bugs there are.
Once you have "created some space", then overwrite the appropriate array entry.
Some other comments:
double[]
, name it myDoubleArray
and initialize it with int
s. All your interactions with your users use int
s as well. I realize that ints can be implicitly converted to doubles, but you should really decide what you want to do and do it consistently. A double literal is just a number with a decimal point like 3.14152
System.Console.WriteLine($"There is an an array with {myDoubleArray.Length} doubles in it, indexed 1 to {myDoubleArray.Length}.");
int.TryParse
and double.TryParse
. They allow you to test for a good value before doing the conversion. That way if the user enters bad data, you can repeat the prompt until he/she enters good data.Enjoy
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.