w3resource logo


C Programming Exercises

C Exercises: Convert a string to double

Secondary Nav

C Variable Type : Exercise-4 with Solution

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

Expected Output :

Output= 4.00

C Code:

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

int main ()
	{
		char input[] = "8.0 2.0";
		char * ptr_end;
		double x, y;

		x = strtod (input,&ptr_end);
		y = strtod (ptr_end,NULL);

		printf ("\nOutput= %.2lf\n\n", x/y);

		return 0;
	}

Solution

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

int main ()
	{
		char input[] = "8.0 2.0";
		char * ptr_end;
		double x, y;

		x = strtod (input,&ptr_end);
		y = strtod (ptr_end,NULL);

		printf ("\nOutput= %.2lf\n\n", x/y);

		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:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number