CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: how do i find decimal ?

1. Junior Member
Join Date
Dec 2017
Posts
2

## how do i find decimal ?

Hi. I wrote this code below to find the average of three numbers. It works, but the answer is always rounded to a whole number. How can I change my code to make this work?

Code:
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Assignment_1_mcdaniel
{
class Program
{
static void Main(string[] args)
{
int f, s, t, r;
Console.WriteLine("Enter Frst Number:");
Console.WriteLine("Enter Second Number:");
Console.WriteLine("Enter Third Number:");
r = (f + s + t) / 3;
}
}
}```
Last edited by 2kaud; December 11th, 2017 at 04:23 AM. Reason: Added code tags

2. Member +
Join Date
Feb 2017
Posts
567

## Re: how do i find decimal ?

Originally Posted by 1236x
How can I change my code to make this work?
It's because you are using integers (int) throughout and integers are whole numbers. If you want decimal numbers you should use floating point numbers ( float or double). I recommend double as first choice.

Assuming you really want f, s and t to be integers you only need to declare r a floating point variable. Note that 3 is an integer literal whereas 3.0 is a floating point literal. To make your intentions crystal clear you could do this,

Code:
```int f, s, t;
double r;
//
r = double(f + s + t) / 3.0;```
The f+s+t summing is performed using integer arithmetic and then explicitly converted to a floating point. This sum is then divided with the floating point literal 3.0 and finally the result is assigned to the floating point variable r.
Last edited by wolle; December 14th, 2017 at 10:54 AM.

3. ## Re: how do i find decimal ?

[moved from C++ (Non Visual C++ Issues) forum]

4. ## Re: how do i find decimal ?

[When posting code, please use code tags so that the code is readable. Go Advanced, select the formatted code and click '#'. Cheers!]

5. ## Re: how do i find decimal ?

Wait... This isn't even C++/CLI, it's C#!

6. ## Re: how do i find decimal ?

Originally Posted by Eri523
Wait... This isn't even C++/CLI, it's C#!
OK!
The thread was moved from Managed C++ and C++/CLI forum.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•