Signed int array typecast C# - c#

When I run the following code:
public int[] finalResult = new int[dimension];
public float[] calculatedValue = new float[dimension];
.....
.....
finalResult[i] = (int) Math.Floor(calculatedValue[i]);
Console.WriteLine( "calculated:" + calculatedValue[i]
+ " final:" + finalResult[i]
+ " test: " +(int) Math.Floor(calculatedValue[i]));
The output is:
calculated:-0.02043936 final:0 test:-1
Why is "final" different from "test" when they are generated from exactly the same code? Which one is wrong, and why?
even simpler, and smaller fragment
finalResult[i]=(int)Math.Floor(-3.0002);
Console.WriteLine( "final: "+ finalResult[i]+ " test:" +(int)Math.Floor(-3.0002));
output
final:0 test:-4
The remaining of the code is irrevelant as below proves
I tried the following lastly,
public int[] junkArray = new int[dimension];
junkArray[i]=(int)Math.Floor(-3.0002); //Junk Array is only assigned here in whole code
Console.WriteLine( "final: "+ (int) junkArray[i]+ " test:" +(int)Math.Floor(-3.0002));
I get output as final:0 test:-4

Here's what I think is actually happening. Bear in mind that I'm making assumptions here, since the code you've provided doesn't compile and when I try to adapt it I always get the correct results that I'd expect. I've thus tried to think of ways to produce the results you're getting by making a deliberate mistake:
using System;
namespace ConsoleApplication1
{
class Program
{
private static int dimension = 1;
public static int[] junkArray = new int[dimension];
static void Main(string[] args)
{
Method1();
Method2();
}
static void Method1()
{
int i = 0;
junkArray[i] = (int)Math.Floor(-3.0002);
}
static void Method2()
{
int i = 0;
int[] junkArray = new int[dimension];
Console.WriteLine("final: " + (int)junkArray[i] + " test:" + (int)Math.Floor(-3.0002));
}
}
}
This produces the results you're seeing:
final:0 test:-4
I've split the code into two methods, one method which is doing the "calculation" and another which does the "presentation". However, for some reason (lack of caffeine, whatever) my second method also declares an array variable that is hiding/shadowing the field that contains our computed results. This isn't illegal, but it means that when I read from junkArray in my Console.WriteLine method call I'm reading from a different junkArray to the one I wrote my results to earlier.
This may not be what's happening, but it's a possibility and without seeing your actual code it's the best guess I can offer. Have a look and make absolutely sure that the array you're reading from is definitely the same array you wrote your results to, rather than a second array that's "shadowing" the first.

If I test the code
var final = new int[1];
var calc = new[] { -0.02043936f };
final[0] = (int)Math.Floor(calc[0]);
Console.WriteLine(
"calc:{0} final:{1} test:{2}",
calc[0],
final[0],
(int)Math.Floor(calc[0]));
unsuprisingly I get the output
calc:-0.02043936 final:-1 test:-1
So, something else is wrong with your code.

There are two things happening here
First - -0.02043936 is a calculated value
Now you are applying math.floor on it. What it will do is, it will floor the value and return a double which will again be a significantly small number.
Now you are casting it to an integer. while doing so, as it is more close to zero, it will turn it out to zero.
To prove this, make the calculated value -0.62043936 or something like and you will get -1 as per your expectation

Related

Unable to print whole list to console

Keep getting the following message when printing a list on console.
System.Collections.Generic.List`1[System.Int32]
This is the console code. It is designed to generate a Fibonacci sequence of a given length. I have tried using the ToString() method, but that doesn't work either. I have built the algorithm in Java so i know that the issue, is fundamentally a C# problem. The issue is resolved if print i print the list elements individually, but i can't print the whole list.
class Program
{
public static void Main(string[] args)
{
Fibonacci fibo = new Fibonacci();
Console.WriteLine(fibo.getSequence(9));
Console.ReadLine();
}
}
class Fibonacci
{
public List<int> getSequence(int length)
{
List<int> results = new List<int>();
results.Add(1);
results.Add(1);
int counter = 0;
while (counter != length - 2)
{
int num1 = results[results.Count - 1];
int num2 = results[results.Count - 2];
results.Add(num1 + num2);
counter++;
}
return results;
}
}
You're returning a List<int>. To print it, you have to e.g. iterate over it
foreach(var i in fibo.getSequence(9)) {
Console.WriteLine(i);
}
Or you can use String.Join()
Console.WriteLine(String.Join(" ", fibo.getSequence(9)));
You are trying to print the object directly to console try iterating over list and print them wherever returned.
for (var item in returned)
Console.WriteLine(item)
if using a custom Type. keep in mind that you have defined its to string method.
Change your Main() to read:
public static void Main(string[] args)
{
Fibonacci fibo = new Fibonacci();
foreach(var element in fibo.getSequence(9))
{
Console.WriteLine(element);
}
Console.ReadLine();
}
Explanation
Look at what you're passing to Console.WriteLine() in your example. getSequence() is returning a list, so you're passing a list to WriteLine(). WriteLine will ToString() on the collection which, by default, will render out the type. If you pass it each individual element (int), it will call ToString() on each one and give you the number.
This is based on the assumption that you want a line per element. If not, look into using String.Join

How can I find an Index in an array using a value that exists in another array and THAT array?

I have a c# class that looks like this:
public class MemberData
{
public int meme_ck;
public string meme_name;
public bool meme_active;
public MemberData(int ck2, string name2, bool active2)
{
meme_ck = ck2;
meme_name = name2;
meme_active = active2;
}
}
I have made two arrays out of that class:
private MemberData[] memarray1 = new MemberData[10000];
private MemberData[] memarray2 = new Memberdata[10000];
Over the course of my application I do a bunch of stuff with these two arrays and values change, etc. Member's name or active status may change which results in the ararys becoming different.
Eventually I need to compare them in order to do things to the other one based on what results are kicked out in the first one.
For example, member is de-activated in the first array based on something application does, I need to update array 2 to de-activate that same member.
I am trying to use some database design philosphy with the int CK (contrived-key) to be able to rapidly look up the entry in the other array based on the CK.
Since I can't figure it out I've had to resort to using nested for loops like this, which sucks:
foreach (Memberdata md in memarray1)
{
foreach (Memberdatamd2 in memarray2)
{
if (md.ck = md2.ck)
{
//de-activate member
}
}
}
Is there a better way to do this? I just want to find the index in the second array based on CK when I have the CK value from the first array.
Any other tips or advice you have about structure would be appreciated as well. Should I be using something other than arrays? How would I accomplish this same thing with Lists?
Thanks!
Should I be using something other than arrays?
Yes. Don't use arrays; they are seldom the right data structure to use.
How would I accomplish this same thing with Lists?
Lists are only marginally better. They don't support an efficient lookup-by-key operation which is what you need.
It sounds like what you want is instead of two arrays, two Dictionary<int, MemberData> where the key is the ck.
I totally agree with Eric Lippert's answer above. It is better you do not use Array.
Same thing can be achieved using List<MemberData>. You can use LINQ as well to query your DataStructure.
Following is one of the way just to achieve your result using array
class Program
{
static MemberData[] memarray1 = new MemberData[10000];
static MemberData[] memarray2 = new MemberData[10000];
static void Main(string[] args)
{
for (int i = 0; i < memarray1.Length; i++)
{
memarray1[i] = new MemberData(i + 1, "MemName" + i + 1, true);
memarray2[i] = new MemberData(i + 1, "MemName" + i + 1, true);
}
// SIMULATING YOUR APP OPERATION OF CHANGING A RANDOM ARRAY VALUE IN memarray1
int tempIndex = new Random().Next(0, 9999);
memarray1[tempIndex].meme_name = "ChangedName";
memarray1[tempIndex].meme_active = false;
//FOR YOUR UDERSTADNING TAKING meme_ck IN AN INTEGER VARIABLE
int ck_in_mem1 = memarray1[tempIndex].meme_ck;
//FINDING ITEM IN ARRAY2
MemberData tempData = memarray2.Where(val => val.meme_ck == ck_in_mem1).FirstOrDefault();
// THIS IS YOUR ITEM.
Console.ReadLine();
}
}

How to write a function that takes an integer as a parameter and calculates and returns the squared value

Ahoy! I have just started methods but I am a tad confused when it comes to methods with math. First post so be nice :) I'm aware I out in NumberToSquare way too many times!
Write a program that asks the user to enter a number. In your program write a function called SquareValue that takes an integer parameter and calculates the square of integer parameter and returns this squared value. Your program should take this returned square value and display it. An example of the output is:
Please enter a number to square: 8
/ 8 squared is: 64
What I have so far is not so comprehensible. I thought along a few different avenues and was unsure as to what to delete. Help please.
namespace SquareValue
{
class Program
{
static void Main(string[] args)
{
int number=NumberToSquare();
SquareValue(NumberToSquare * NumberToSquare);
string output;
Console.ReadKey();
}
public int SquareValue(NumberToSquare, NumberToSquare);
{
int result = NumberToSquare * NumberToSquare;
return result;
Console.WriteLine("{0} squared is "+result");
}
public int NumberToSquare()
{
Console.WriteLine("Please enter a number to square: ");
int NumberToSquare = Console.ReadLine();
return NumberToSquare;
}
}
I see no reason to over complicate this:
public int Square(int x)
{
return (x * x);
}
or
public int Square(int x)
{
return Math.Pow(x,2);
}
Or just use Math.Pow as it exists with 2 as the Power Of number.
You seem very green on programming and I'm not sure SO is a place to go to learn the basics, but I'll run through what you've done and explain what's going wrong.
Your original program concept is fine but there are many issues with basic syntax. I understand you mightn't be familiar with reading compiler errors so I'll explain the errors that I see just reading through the code...
You put a ; at the end of the SquareValue(..., ...) method which teeminates the declaration so the body in braces isn't part of the method, then things go haywire later on.
You're not passing in the value captured from the NumberToSquare method...
int number=NumberToSquare();
SquareValue(NumberToSquare * NumberToSquare);
NumberToSquare isn't a defined variable so NumberToSquare * NumberToSquare can't calculate, what you'd want is number * number where `number is the value entered by the user.
Your definition of int SquareValue(NumberToSquare, NumberToSquare) expects two parameters although you haven't speified the type. It should be
int SquareValue(int NumberToSquare, int NumberToSquare)
but you have the same variable declared twice which is another error and then you aren't passing two parameters anyway. You want to multiply a number by itself therefore you only have a single source number so why declared two parameters? You need a single parameter method
int SquareValue(int NumberToSquare)
and call like this
int number=NumberToSquare();
SquareValue(number);
Now the SquareValue() method returns an int but you never capture it in the calling code and display the result in the method. Follow the idea in this app that the Main method will do all the orchestration and display, but the SquareValue() method should ONLY do a calculation and not any I/O. I'd also rename the NumberToSquare() method a as what is actually happening ... GetNumberToSquareFromUser().
And there's also a stray " before the closing bracket.
Console.WriteLine("{0} squared is " + result");
And you defined a string output variable which is never used.
And your methods need to be static because main(..) is a static method, not instance. If you declare a Squaring class and instantiated it then you could call non static methods from that.
Also ReadLine() returns a string which can't be assigned to an int.
And finally the result line is implicitly using String.Format behind the scenes but you haven't specified the original number for the {0} token. You could also use interpolation. You could do either of these
Console.WriteLine("{0} squared is " + result, number);
Console.WriteLine($"{number} squared is " + result);
So here's your program revised
class Program
{
static void Main(string[] args)
{
int number = GetNumberToSquareFromUser();
int result = SquareValue(number);
Console.WriteLine("{0} squared is " + result, number);
Console.ReadKey();
}
public static int SquareValue(int numberToSquare)
{
return numberToSquare * numberToSquare;
}
public static int GetNumberToSquareFromUser()
{
Console.WriteLine("Please enter a number to square: ");
int NumberToSquare = int.Parse(Console.ReadLine());
return NumberToSquare;
}
}
I hope this help, I know it's alot to take in, but I hope you take the time to read and really understand rather than just blindly submit the revised version.
When writing your methods, make them reusable. When you start using a method to output to the console in addition to its primary purpose (i.e. to square a number), its re-usability becomes minimal. It is much better to keep specific code in your main method, and put sub tasks into separate methods, such as squaring a number. Now, whenever you need to square a number, you already have a perfectly good method for that.
I didn't handle the case for users entering bad input, but that can be done in the else of the TryParse if block.
static void Main(string[] args)
{
int squredNum = 0;
int NumberToSquare = 0;
Console.WriteLine("Please enter a number to square: ");
if(int.TryParse(Console.ReadLine(), out NumberToSquare))
{
squredNum = SquareValue(NumberToSquare);
Console.WriteLine("{0} squared is {1}", NumberToSquare, squredNum);
}
Console.ReadKey();
}
static int SquareValue(int numberToSquare)
{
return numberToSquare * numberToSquare;
}
p.s. I would not recommend using Math.Pow() to square a number. No need to kill a fly with a bazooka!
Here is an example of such program with robust handling:
using System;
namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter value to square or X to exit");
var line = Console.ReadLine();
if (line == null)
continue;
if (line.Trim().Equals("X", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("Exitting ...");
break;
}
int result;
if (!int.TryParse(line, out result))
continue;
Console.WriteLine(result * result);
}
}
}
}
See the docs online, understand each statement, write your very own program then as your teacher will likely figure out you didn't pull that solely by yourself :)

How can I modify a function's behavior based on if it is being assigned to a variable?

As in the title.
I know this is possible in other languages - is it in C#?
If the question title isn't clear, i would like something that does (something like) this:
MyClass exampleObject1 = new MyClass(...)
exampleObject1.sort() //sort method detects that value is not being assigned and performs sort in place.
MyClass exampleObject2 = exampleObject1.sort() //method detects assignment and returns new sorted object leaving original untouched.
is this something that's possible without resorting to magic? If it is possible, but in some nasty way, what is that way?
EDIT: for those wanting to see an example where you can do this (in python): here. Note that i caveat it with the issue that it does not always work - but this is only in relation to the way i did it when i answered the question. Now i know more about inspect, and you can get all the information you need from the stack to work out if it is being assigned anywhere or not.
Of course, you definitely shouldn't be doing this, but since the OP is more interested if it could be done for curiosity sake, then here is a snippet of code that demonstrates this capability:
class SomeWeirdClass
{
private bool sortApplied = false;
private List<int> elements;
public IList<int> Elements
{
get
{
if(sortApplied)
{
elements.Sort();
sortApplied = false;
}
return elements;
}
}
public SomeWeirdClass(IEnumerable<int> elements)
{
this.elements = elements.ToList();
}
public SortedWeirdClass Sort()
{
sortApplied = true;
return new SortedWeirdClass(this);
}
public class SortedWeirdClass
{
SomeWeirdClass parent;
internal SortedWeirdClass(SomeWeirdClass parent)
{
this.parent = parent;
}
public static implicit operator SomeWeirdClass(SortedWeirdClass sorted)
{
sorted.parent.sortApplied = false;
var elementCopy = new int[sorted.parent.elements.Count];
sorted.parent.elements.CopyTo(elementCopy);
var result = new SomeWeirdClass(elementCopy);
result.Sort();
return result;
}
}
}
Now using it in a program:
static void Main(string[] args)
{
SomeWeirdClass original = new SomeWeirdClass(new[] { 5, 1, 4, 3, 2 });
Console.WriteLine("Original Data: ");
Console.WriteLine(string.Join(" ", original.Elements));
SomeWeirdClass copy = original.Sort();
Console.WriteLine("Original Data after Sort and Assignment: ");
Console.WriteLine(string.Join(" ", original.Elements));
Console.WriteLine("Sorted Copy:");
Console.WriteLine(string.Join(" ", copy.Elements));
original.Sort();
Console.WriteLine("Original Data after Sort without Assignment: ");
Console.WriteLine(string.Join(" ", original.Elements));
}
The program outputs:
Original Data:
5 1 4 3 2
Original Data after Sort and Assignment:
5 1 4 3 2
Sorted Copy:
1 2 3 4 5
Original Data after Sort without Assignment:
1 2 3 4 5
The hack here is that sorting actually creates a temporary class which wraps the original. Unless that result is implicitly cast to the original type via assignment, the sorting effects will be applied to the original dataset. If assignment is made, the sorting is cancelled, and a copy is made for the new variable.
It is not possible in a reliable way. The compiler can optimize
MyClass exampleObject2 = exampleObject1.sort(); to exampleObject1.sort(); if exampleObject2 is not used.
To answer a slightly different question: you could return a Lazy<MyClass>. So you can do the sort only if the result is actually used.
Split the Copy and Sort methods into two distinct methods. If I want to sort a copy, I should be responsible for copying before I sort. For example:
var copy = myCollection.Copy();
copy.Sort();
The goal should be making it clear what your function is doing to any calling code. Different behavior based on usage is only going to lead to bugs, at least in the C# world.

Assigning String Data to a Varaible

I'm new to programming in general, but I've thoroughly searched this and can't find anything that is related to this, but I admit it may be because I don't know 100% what to look for. So I apologize if this is redundant or extremely simple.
I'm working on an assignment in C# where we have to create a sentinel loop asking for a product # and quantity. With that, we make a calculation for cost and write all of that information to a private string variable.
In order to avoid academic dishonesty, I'll just ask about some code slightly different than the example.
private string test1;
public string Test1
{
get
{
return test1;
}
set
{
test1 = value;
}
}
}
...
Console.WriteLine("Enter a number");
int number1 Convert.ToInt32(Console.ReadLine());
int number2 = (number1*3);
This is the part that I can't figure out. I've tried it several ways:
test1 = ("{0}, {1}", number1, number2);
and
test = ("{0}, {1}", "number1", "number2");
as well as both of those iterations without parenthesis. I also can't get it to work even when "numer1" and "number2" are string variables.
Is it possible to assign this type of string data to a variable?
I'm not entirely sure what you edited, the reason your code isn't working is because your not calling String.Format. You can often ignore String.Format when you utilize a Console.WriteLine which has the functionality built into it.
Which is where I believe your confusion is occurring. To resolve your issue:
public class Example
{
private string example;
public Example(string example)
{
this.example = example;
}
public string Demo
{
get { return example; }
private set { example = value; }
}
}
The following class should be straight forward, we have our parameter which will assign a value to our Demo through the Constructor. So to store our value, as a String we would do the following:
var total = 0;
var number = 0;
if(int.TryParse(Console.ReadLine(), out number)
total = number * 3;
var example = new Example(String.Format("{0}, {1}", number, total));
Console.WriteLine(example.Demo);
So, the TryParse won't throw an exception if it fails to convert the user input. Then to format the String we utilize the String.Format. Then you can see such output by calling example.Demo.
Hopefully this clarifies your problem a bit.

Categories

Resources