Hi all,

I was trying to write a C program which round off the decimal number, here main intension is decimal digits can be of N digits. So problem I was facing to get last digit on which I have to take decision.

Please check below C code -

suppose our input is stored in "input" variable .

I tried this program with input = 10.58 , 10.53 and 10.57
strange its working for starting 2 inputs and I am getting output =
10.6 , 10.5 but for last one I am not getting right output I am getting output same as input 10.57

Please help me where I am doing worng ?

i= 1;
		b= input; 
		
		while(1)
		{	
			b= b*10;
				
			if(b== ((float)(int)b))
			{
	
				d= (int)b%10;
		
				b= (int)b/10;
		
				if(d>= 5)
				{
					b= b+1;
				}

				i= i-1;
				while(i)
				{
					b= b/10;
					i--;
				}
				
				break;
	
		
			}
			else
			{
				i++;
		
			}	
			
		}

You are attempting to round based on the .5, not the .57. Each answer should be 11.

Did you try desk-checking the code? Assume input = 10.57. You write down the result for each step and keep track of all the variables: b= b*10; -- what's the value of b? d= (int)b%10; -- what's the value of b and d?
etc.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.