w3resource logo


C Programming Exercises

C Exercises: Convert a string to a double

Secondary Nav

C Variable Type : Exercise-14 with Solution

Write a C program to convert a string to a double.

Expected Output :

Input a number : 25                                                                                          
 The original number is : 25.000000                                                                           
 After division by 2 the number is : 12.500000 

C Code:

#include<stdio.h>
#include<stdlib.h>

int main ()
	{
		double num1,num2;
		char my_array [256];
		printf ( "\n Input a number : " );
		fgets (my_array, 256, stdin);	
		num1 = atof (my_array);
		num2 = num1/2;
		printf (" The original number is : %f \n", num1);
		printf (" After division by 2 the number is : %f\n\n", num2);
		return 0;
	}
	

Solution

#include<stdio.h>
#include<stdlib.h>

int main ()
	{
		double num1,num2;
		char my_array [256];
		printf ( "\n Input a number : " );
		fgets (my_array, 256, stdin);	
		num1 = atof (my_array);
		num2 = num1/2;
		printf (" The original number is : %f \n", num1);
		printf (" After division by 2 the number is : %f\n\n", num2);
		return 0;
	}
	

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program