Math based C#

Incrementation

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • 4

49 Replies - 3992 Views - Last Post: 20 October 2010 - 01:56 PM Rate Topic: -----

#31 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 201
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Math based C#

Posted 19 October 2010 - 08:54 AM

I assumed that you used this code:

Spoiler


I thereby only focus on the code itself, not on the streamwriter.

According to you program flow:
                    str = Console.ReadLine();
                    x = Int32.Parse(str); 
                    for (int i = 1; i <= x; i++)
                    {
                        sw.WriteLine(10 * (i * i));
                    }
                    if (x > 10)
                        Console.WriteLine("Hey! The number should be 10 or less!");
                    else
                       if (x < 0)
                        Console.WriteLine("Hey! The number should be 0 or more!");
                    else
                        Console.WriteLine("Good job!");



Your first parsing the given value [aka the user input] and then run the calculation. Only after the calculation, it checks whether your input is between your bounds!
This has as consequence that your calculation will always run (or better spoken print) the amount of the user specified number, regardless the bound. You should use your conditional formatting earlier (that's point 1) and find a manner to let the user specify a new number between the bound.

Too bad, I am a bit sick now, otherwise I would've tried to find something for you. Hope this helps you out ^^

Edit:
Ok, I could not resist myself to make a global thingie (despite I am sick and should rest, but I don't wanna :whistling: )

Anyways, I would do it in this manner:
Spoiler


Probably not the best way to get it all around and so on, but it does what it does. If you have questions about it, don't hesitate to ask.
[ow and I did remove your streamwrite, because I was a bit lazy, sorry >< However, you should get the general idea out of this ^^]

This post has been edited by karabasf: 19 October 2010 - 09:10 AM

Was This Post Helpful? 1
  • +
  • -

#32 Sparukus  Icon User is offline

  • D.I.C Head

Reputation: -11
  • View blog
  • Posts: 190
  • Joined: 05-April 10

Re: Math based C#

Posted 19 October 2010 - 10:37 AM

No I tryed with this code:

                        for (int i = 1; i <= numberOfTerms; i++) 
                        {
                            try 
                            {
                                checked 
                                {
                                    int currentTerm = 10 * i * i; 
                                    Console.WriteLine(currentTerm); 

                                 

                                    if (i == 1) stream.WriteLine("Value of n" + "," + "Term"); 
                                    

                                    stream.Write(i.ToString() + ","); 

                                    if (i != numberOfTerms) stream.WriteLine(currentTerm.ToString() + ","); 
                                    else stream.WriteLine(currentTerm.ToString()); 
                                    if (numberOfTerms > 100)
                                        Console.WriteLine("Hey! The number should be 10 or less!");
                                    else
                                        if (numberOfTerms < 0)
                                            Console.WriteLine("Hey! The number should be 0 or more!");
                                        else
                                            Console.WriteLine("Good job!");
                                }
                            }

Was This Post Helpful? 0
  • +
  • -

#33 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 924
  • View blog
  • Posts: 926
  • Joined: 30-September 10

Re: Math based C#

Posted 19 October 2010 - 10:52 AM

Hello again,

Karabasf if right when he says you need to check input before you do the calculation. If you just add this statement directly below the if statement with the Math.Abs() call in it (see previous code I posted in spoiler tags), it should do the job.

 if (numberOfTerms > 100)
                        {
                            Console.WriteLine("\nYour number was above 100!");
                            continue;
                        }



The continue statement will cause the while loop to loop again and display the initial prompt. Obviously though, with my code, if the user enters a negative number, the program automatically converts it to a positive number. If you don't want that, you could delete the if statement that checks for a negative number in my code, and add this in place of the statement above:

 if (numberOfTerms > 100 || numberOfTerms < 0)
                        {
                            Console.WriteLine("\nYour number needs to be between 0 and 100 inclusive!");
                            continue;
                        }


This post has been edited by CodingSup3rnatur@l-360: 19 October 2010 - 10:56 AM

Was This Post Helpful? 1
  • +
  • -

#34 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 201
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Math based C#

Posted 19 October 2010 - 10:58 AM

In that case, you should move this:
if (numberOfTerms > 100)
   Console.WriteLine("Hey! The number should be 10 or less!");
else if (numberOfTerms < 0)
   Console.WriteLine("Hey! The number should be 0 or more!");
else
   Console.WriteLine("Good job!");



To somewhere else (preferably below your parse statement.

What your code is currently doing:
1) User inputs a value (suppose I am the user :P and a bit sick (I am soo :P)) and enters a value like 200
2) It passes your test and executes your for-loop (and therefore writing 200 lines in the document)
3) But in your for-loop you're evaluating your bounds. So, it writes 200 lines in your document, while the console probably says 200 times "Hey, value should be below 100!"

Thus, as stated in an earlier post, you need to move your condition/bound evaluation directly after you parse and couple it with your loop.

Personally, I still would do it like my previous post. The principle is the same.

Still having questions? Do not hesitate to ask ^^

Edit:
Off course, there are other methods to obtain the same results. I probably shouldn't be so 'free-minded' and keep throwing exceptions in my programs ><

This post has been edited by karabasf: 19 October 2010 - 11:02 AM

Was This Post Helpful? 1
  • +
  • -

#35 Sparukus  Icon User is offline

  • D.I.C Head

Reputation: -11
  • View blog
  • Posts: 190
  • Joined: 05-April 10

Re: Math based C#

Posted 19 October 2010 - 11:40 AM

All done woop you guys are awesome!

Man I love coding :D hmm is C# capable of telling excel to print out a graph inside the csv file? So if I input 50 numbers and open the excel file it should display the numbers but also in some cell it will deisplay a graph starting from 0 to numberOfTerms inputed by user?

Thanks so much for all the help so far guys!! Much appreciated.
Was This Post Helpful? 0
  • +
  • -

#36 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 924
  • View blog
  • Posts: 926
  • Joined: 30-September 10

Re: Math based C#

Posted 19 October 2010 - 11:54 AM

Glad you got it sorted. It is possible to interop with Excel and draw graphs from c#. I don't have a great deal of experience with it, but I think I can create a graph and create the .csv simultaneously. However, I'm not sure how you should open an already existing .csv and draw a graph from that purely because you have just calculated all the data, so why not use it there and then instead of opening the file and reading the data from there. So, I think you would want to store the calculated terms in a collection, then loop through the collection and occupy an Excel worksheet with the values, then draw a graph from there. I can try and help you if you want though?

This post has been edited by CodingSup3rnatur@l-360: 19 October 2010 - 12:25 PM

Was This Post Helpful? 1
  • +
  • -

#37 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 201
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Math based C#

Posted 19 October 2010 - 11:54 AM

No problem at all^^

And well, according to this source: http://support.microsoft.com/kb/302084

It is possible to achieve such. However, I am not that experienced in C# (not yet) to explain it to you sufficiently :P
But maybe it is worth a shot for you to try such, don't you think? ^^

Edit:
Maybe it is better to make a .csv file, while writing values in Excel or something?

This post has been edited by karabasf: 19 October 2010 - 11:56 AM

Was This Post Helpful? 1
  • +
  • -

#38 Sparukus  Icon User is offline

  • D.I.C Head

Reputation: -11
  • View blog
  • Posts: 190
  • Joined: 05-April 10

Re: Math based C#

Posted 19 October 2010 - 12:20 PM

aahhh HAAA told you it would get complicated ;) wooo now im really learning something going to check all the sources and will come back with code and we could try solve it.

If you guys might struggle or havent came across it can gaurantee I will fail :) will post in a while!
Was This Post Helpful? 0
  • +
  • -

#39 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 201
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Math based C#

Posted 19 October 2010 - 12:40 PM

Hahaha, well, complex issues are the most interesting one, I think.

For example, I am currently working for an ICT-company in my village and they want me to program an API for them on a platform (maybe program is a better word) which is not commonly used. (well, it's a new platform/program) (and yes, they use .NET and C# for it :P)
But I like to research and experiment with these kind of things. Live curious :P

And I am still learning C#, but en general I mastered the basics (which is a must) and started some own (simple) 'programs'. Some current projects of my are:
- A converter. Convert from decimal, binary, octal, hexadecimal to decimal, binary, octal and hexadecimal
- Guess the number. Well, this sounds boring, but I am building it massively out >< It saves the highscore, has a hardmode, has a cheatcode and some eater eggs in it ><
- A timer (well, not started yet, but I am planning to start it)



And I got an idea from the forum, the cubic root :P I got a bit curious by the application of Newton's method, so... Still worth a shot trying things.

Live curious, like I said earlier ^^ :P
Was This Post Helpful? 1
  • +
  • -

#40 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 924
  • View blog
  • Posts: 926
  • Joined: 30-September 10

Re: Math based C#

Posted 19 October 2010 - 01:05 PM

I don't know if this fits in with what you want the application to do, but the easiest way to do this would be to skip the creation of a .csv file. Instead of calculating the terms and storing them in the .csv file, store them in a List. Then, create a new Excel WorkSheet from this list, and draw the graph in the WorkSheet. I don't know if there is any specific reason you want the .csv file... That is the way I would do it anyway.

You can still keep the .csv file creation part of the code if you really want a .csv for whatever reason, but to draw the graph, I would suggest creating a new, separate WorkSheet, filling it with your data, then drawing the graph using the data in that WorkSheet.

This post has been edited by CodingSup3rnatur@l-360: 19 October 2010 - 01:28 PM

Was This Post Helpful? 1
  • +
  • -

#41 Sparukus  Icon User is offline

  • D.I.C Head

Reputation: -11
  • View blog
  • Posts: 190
  • Joined: 05-April 10

Re: Math based C#

Posted 19 October 2010 - 01:34 PM

Yeah im trying loads of different things, i prefer to reedit code i understand it better how the structures folk are using, CBT nuggets has a good video tutorial on it for C# but cant get a hold of it atm. :(

But if i keep trying loads of different examples and methods and little tests for my self I should eventually know how to do everything.

Re: on the cvs not specifically important just I had it in mind for an excel file so thought that was how you went about it.

I think its wayyyy above me tho... :( Wouldnt know how to go about it atm.

//Add a chart
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject xlChart = (Excel.ChartObject)xlCharts.Add(30,30,30,30);
Excel.Chart chartPage = xlChart.Chart;

//set the source data and the chart type.
Excel.Range chartRange = xlWorkSheet.get_Range("Value of User Input", "Calculation");
chartPage.SetSourceData(chartRange, missingValue);
chartPage.ChartType = Excel.XlChartType.xlColumnClustered; 


something along the lines like so?
Was This Post Helpful? 0
  • +
  • -

#42 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 201
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Math based C#

Posted 19 October 2010 - 01:45 PM

I am not quite sure about that piece of code.

IF it's only for drawing graphs, according to my link, you should use this:
	//Add a Chart for the selected data.
	oWB = (Excel._Workbook)oWS.Parent;
	oChart = (Excel._Chart)oWB.Charts.Add( Missing.Value, Missing.Value, 
		Missing.Value, Missing.Value );

	//Use the ChartWizard to create a new chart from the selected data.
	oResizeRange = oWS.get_Range("E2:E6", Missing.Value ).get_Resize( 
		Missing.Value, iNumQtrs);
	oChart.ChartWizard( oResizeRange, Excel.XlChartType.xl3DColumn, Missing.Value,
		Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value, 
		Missing.Value, Missing.Value, Missing.Value, Missing.Value );
	oSeries = (Excel.Series)oChart.SeriesCollection(1);
	
        //Obtain the X-values for the data
        oSeries.XValues = oWS.get_Range("A2", "A6");

	for( int iRet = 1; iRet <= iNumQtrs; iRet++)
	{
		oSeries = (Excel.Series)oChart.SeriesCollection(iRet);
		String seriesName;
		seriesName = "=\"Q";
		seriesName = String.Concat( seriesName, iRet );
		seriesName = String.Concat( seriesName, "\"" );
		oSeries.Name = seriesName;
	}	



As I said, I am not far enough with C# to understand such. Furthermore, I think this is even a step beyond C#, because you're not looking at a stand-alone application, but more to an application which uses C#. And that application (in this case excel) has it's own methods to get things done.

Though, I think you can get the first part done, that is filling the Excel sheet with the values. Personally, I think you should complete (or maybe better said, master) that part first, before you move to making a graph. This is mainly due to the fact that (I studied the code globally) the chart(wizard) is dependent of some datarange.

My advice is therefore: focus on filling your excel sheet with your data first ^^
Was This Post Helpful? 0
  • +
  • -

#43 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 924
  • View blog
  • Posts: 926
  • Joined: 30-September 10

Re: Math based C#

Posted 19 October 2010 - 02:14 PM

Right. As you don't need the .csv file especially, I shall go with my idea of creating the WorkSheet directly if that's okay? A couple of points on the code you have posted...

1) I think the get_range function requires cell references to be passed to it
2)You need to open and fill an Excel WorkSheet
3) You need to save that Worksheet

Ahh....scrap that... I've just had a quick look on google and found that snippet you posted. I think this should actually be quite easy...


Below is code for a method that should do what you require. Seeing as you have found most of what is required, I see no real harm in this. However, please note that you have to create the list and add items to the list in the Main method, and then call this method. Make sure you read the comments though, and ask if you don't understand anything. I shall post all the code I have just for clarity (you should have the vast majority of this already, there are just few extra lines in the drawExcelGraph method mainly).

Anyway, have a read, make sure you understand it, and post back with how it goes, any questions you may have, any other things you require etc.

Copy and paste the code into your IDE (or whatever you are using) before you read it, as it may look a bit messy and complicated in code tags :):

Spoiler


Please note the call to the static Collect method of the GC class (GC.Collect()). This forces the garbage collector to run (you can also pass arguements to the method to specify which generation to collect etc (generations are, in basic terms, a mechanism to make garbage collection as efficient as possible and it involves placing 'older' objects that have survived multiple garbage collections in higher generations that get garbage collected less often. This is based on the assumption that the older objects will stay referenced for, more or less, the life time of the application as they are key objects in the application, where as new objects (generation 0) are likely to be temp variables etc. Basically, by using generations, the older, more important objects are not bothered as often as they would otherwise be.

Anyway, there are only really two circumstances when you should force the garbage collector to collect:

1)When you have just finished creating a very large number of objects
2) When you are about to enter into a part of an application you do not want interrupted by a Garbage Collection (as, for example, during a garbage collection, all current, active threads are suspended)

I am a bit dubious about the use of the GC.Collect() here. I don't really think it is necessary here...but hey, it can't do any real harm in an application of this size I suppose. Notice also that I have added the call to GC.WaitForPendingFinalizers();. This is generally recommened practice after a GC.Collect() call as it allows all finalizable objects to perform any clean up they need to do (in very simple terms anyway). It's good to get into the habit of doing these things early, even if they will have very limited effects or no effects in your current application.

Just thought i'd let you know :).

This post has been edited by CodingSup3rnatur@l-360: 19 October 2010 - 04:00 PM

Was This Post Helpful? 1
  • +
  • -

#44 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 201
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Math based C#

Posted 19 October 2010 - 02:39 PM

I think you copied your code twice :P

The correct code should be this:
Spoiler


No offense though ^^

Personally, I'd recommend to remove the .csv functionality. You're already saving a .xls(x)

Furthermore, what's maybe interesting is to remove the user input and let the program calculate from 1 to 100 terms or something like that. Or maybe more interesting, let the user specify the initial value. Ideas, ideas :P

Edit:
never mind, you already saw your double pasted code ^^

This post has been edited by karabasf: 19 October 2010 - 02:40 PM

Was This Post Helpful? 1
  • +
  • -

#45 Sparukus  Icon User is offline

  • D.I.C Head

Reputation: -11
  • View blog
  • Posts: 190
  • Joined: 05-April 10

Re: Math based C#

Posted 19 October 2010 - 06:25 PM

OMFG that is actually amazing it CAN BE DONE!!! and it works so well, how on earth could u just throw that together???

I feel even more lost than before at my pittyful attempts lol how long will it take before you know c inside and out like this? Man im speachless!!! To both of you on how well uve helped me out!
Was This Post Helpful? 0
  • +
  • -

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • 4