Write a program that reads a string consisting of a positive integer or a positi
ID: 666732 • Letter: W
Question
Write a program that reads a string consisting of a positive integer or a positive decimal number and converts the number to the numeric format. If the string consists of a decimal number, the program must use a stack to convert the decimal number to the numeric format.
All the conversion code should be written in the main function, but to store the converted value (an int node per each number), the program may use a linked list stack. However, because the textbook used a stack array (p.1128), the program can use either linked list stack or stack array method. Whichever method is selected, the functions and variables in the stack class should be the same.
The important key to convert digit to number is to estimate the value of the digit string. We assume the number is a double, so the program must identify the location of a decimal point, and then divide the digits into a whole-number part and a decimal part. Each digit must be converted into an integer value and stored in a stack list or stack array.
Explanation / Answer
#include <stdio.h>
double stack[50];
void push();
double pop();
void traverse();
int is_empty();
double top_element();
int top = 0;
int main()
{
int s[20],i,j,k,l;
int temp=0;
double res=0,temp1=1;
char a[100],b[100];
scanf("%[^.].%s",&a,&b);
temp=atoi(a);
res=temp;
while(b[i])
{
temp1*=0.1;
push((b[i]-'0')*temp1);
i++;
}
while(is_empty()==0)
{
res+=pop();
}
printf("%lf ",res);
}
void push(double value) {
stack[top] = value;
top++;
}
double pop() {
top--;
return stack[top];
}
int is_empty() {
if (top == 0)
return 1;
else
return 0;
}
double top_element() {
return stack[top-1];
}
Output
Input