Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cin doubt

Status
Not open for further replies.

vbkris

Programmer
Jan 20, 2003
5,994
IN
i am a newbie to c++ i have a doubt

when we give cin the curso appears asking for the use to enter the info

eg:
cout "Enter Number:";
cin >> i;

will display
Enter Number:_(cursor)


i want a default value to be displayed...
like:
Enter Number:95
the use can change it at his option..

is this possible using C++?


i have another doubt
int a,b;
float c;
a=15;
b=16;
c=a/b;
cout << c;
output: &quot;0&quot;

why is it not .975?

if i change a or b to float it gives .975, why?





Known is handfull, Unknown is worldfull
 
In answer to your first question - using cin it is not possible.

In your other question,

c = a/b - what you have is this

float = int/int

The int/int will evalulate to an int
This is then cast to a float

To get the correct value you will need to cast everything:

c = (float) ( (float)a)/((float)b);


Hollingside Technologies, Making Technology work for you.
 
First question: You can't explicitly give a value to be input by default. You can say something to the effect of: &quot;Enter a number (default 6):&quot; and then check to see if they entered anything. If they did, use what they put; if not, use the default.

Second question: mrscary is right, but uses more casting than necessary.
Code:
  int/int   = int    (e.g. 7/5 == 1)
  int/float = float  (e.g. 7/(float)5 == 1.4)
float/int   = float  (e.g. (float)7/5 == 1.4)
float/float = float  (e.g. (float)7/(float)5 == 1.4)
In the first example, int/int, (which is what you have,) dividing an int by an int gives you an int. In this case, you get 1. When you assign that to a float, you get 1 as a float, which is just 1.0.

In each of the other examples, you get the correct value because at least one of the operands was treated as a float. It's unnecessary to cast both operands, and it's also unnecessary to cast the final result before assigning it.
 
thanks guys... but have u come across any program that has satisfied my first question?

Known is handfull, Unknown is worldfull
 
i am a newbie mrscary...

Known is handfull, Unknown is worldfull
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top