• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Tim Cooke
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
  • Piet Souris
Bartenders:
  • Stephan van Hulst

Preincrement used in an expression

 
Ranch Hand
Posts: 267
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The expression is as follows:
quotient /= ++x;
All variables have an integer value of 5.

The answer given is x = 6, quotient = 0.
I get lost at some point. The way I understand preincrement (variable is incremented then reassigned before used in an expression) and postincrement (variable is used then incremented) the answer I thought it would be would be an 1 because the value is incremented then it divides.
Where am I messing up?
 
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since quotient and x both = 5, you end up with quotient = 5/6, which as an int is 0. If you change the variables to floats, you will get quotient = .8333 and x = 6.
Chad
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
quotient /= ++x;

All variables have an integer value of 5.


int quotient = 5;
int x = 5;

quotient /= ++x ;
quotient = quotient / ++x ;
x = x + 1 ;
x = 6 ;
quotient = 5 / 6 ;
quotient = 5 / 6 ;

so --
quotient = 0 ;
x = 6 ;
 
Liar, liar, pants on fire! refreshing plug:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic