c# - Passing one variable by reference and "returning" two variables -


this question has answer here:

so trying pass in 1 variable, money variable, , break 2 variables. stuck , trying figure out how pass 2 values when passed in one. supposed double value of money user , split 2 int values. example value 3.45 , split , print out message, "there 3 dollars , 45 cents in $3.45". understand pass reference, trying figure out said how 2 variables back. , can pass in money variable method know program not right. looking ideas , explanations on how this. thanks

 using system;   static class program  {       //declare constansts       const int one_hundred = 100;       static void main()      {          //declare local variables          double money = 0;           //ask user input money value          console.writeline("please enter money value. (ex. 2.95)");           //store value in variable           money = double.parse(console.readline());            //take variable , call splitmoney method           splitmoney(ref money);            //display message           console.writeline("there {0:d} , {1:d} cents in ${0:f2}", money, dollars cents);            console.readline();      }//end main()        //split money method       //purpose: split money dollars , cents       //parameters: 1 double passed reference       //returns: nothing       static void splitmoney(ref double money)       {             money = (int)(money * one_hundred);             int dollars = (int)(money / one_hundred);             int cents = (int)(money % one_hundred);       }    }//end class program 

for question:

public class splittedmoney {     public int dollars { get; set; }     public int cents { get; set; } } 

you return that. easiest way.

a better way may be:

public struct splittedmoney {     public readonly int dollars;     public readonly int cents;      public splittedmoney(int dollars, int cents)     {         dollars = dollars;         cents = cents;     } } 

this better, splitted dollar still value, using immutable struct way go here.

now, don't use doubles in requires precise decimal calculations. use decimals instead they're designed task. double can lose precision base 10, stored , manipulated in base 2. decimal designed preserve precision in base 10.


here's rewrite of splitmoney using above struct:

  static splittedmoney splitmoney(decimal money)   {         var totalcents = (int)(money * 100);         int dollars = (int)(totalcents / 100);         int cents = (int)(totalcents % 100);         return new splittedmoney(dollars, cents);   } 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -