Reputation: 11
I wrote the following code for this
Given an integer number, Write a C program that displays the number as follows:
For eg., the number 5678 will be displayed as:
5 6 7 8
6 7 8
7 8
8
=>
#include<stdio.h>
#include<math.h>
main()
{
long int x,y,n,z,i=1;
printf("enter no. of digits=");
scanf("%d",&n);
printf("x=");
scanf("%d",&x);
while(i<=n)
{
y=x/pow(10,i);
z=y*pow(10,i);
printf("%d\n",(x-z));
i++;
}
}
The code works(if we ignore the formatting) but does some rounding of and stuff fr some output values ...don't know why?? There are solutions using array and all...but whts wrong with this one??
Upvotes: 0
Views: 1199
Reputation: 1
#include <stdio.h>
#include<conio.h>
void main()
{
int number,i=0;
int digits[8];
scanf("%d"&number);
while(number!=0)
{
digits[i]=numder%10;
number=number/10;
i++
}
for(i=i-1;i>=0;i--){
for(j=i;j>=0;j--){
printf("%d ",digits[j]);
}
printf("\n"):
}
}
Upvotes: 0
Reputation: 35
#include<stdio.h>
#include<math.h>
main()
{
int num, count=0, x,no;
printf("Enter a number\n");
scanf("%d",&num);
no=num;
printf("The number you entered is:\n %d\n",num);
while(num){
num=num/10;
count++;
}
for(;count>1;count--){
x=pow(10,count-1);
printf("%d\n",no%x);
}
}
Upvotes: 0
Reputation: 32510
I'm assuming by "some values" with problems, you're referring to values that have zeroes in them, such as input like 50345
, which will print:
50345
345
345
45
5
rather than:
50345
0345
345
45
5
The problem is that the integer representation of numerical values does not acknowledge leading zeroes as being a unique integer value.
If you must print the values, including leading zeroes, you're going to have to treat your number like a token or string, meaning that a value that has leading zeroes is a unique string value from the version without leading zeroes. This is why the array-versions, which treat the numeral value like a string, work, and your current version does not when presented with this type of input case.
Upvotes: 2
Reputation: 10558
The rounding off you are seeing could be because of the use of int
as data type for all the variables. So something like (5/10)
would be rounded to 0 and not 0.5.
Upvotes: 0