I have this homework exercise I'm having problem with. I'm taking a introductory programing class, and we are working with C.
the exercise wants us to "Write a program that inputs one five-digit number, separates the number into its individuals digits and prints the digits separated from one another by three spaces each.[Hint: use combination of integer divition and the remainder operation.] For example, if the user types in 42139, the program should print. 4 2 1 3 9."
Can anyone help me?? I went online and did some research and this is want i came with.
#include "stdafx.h"
int main()
{
int num;
printf("Enter your five-digit number\n");
scanf("%d", %26amp;num);
while ( num %26gt; 0 )
{
int digit = num % 10;
printf( "%d\n", digit );
num = num / 10;
}
return 0;
}
but this is not what i need.
thank you for your time!
I need help with this C Programing Homework.?
The program you propose seems to be nice but it prints the digits in the wrong order
so I would use the following code instead
for(int divider=10000; divider %26gt;0 ; divider/=10)
{
int digit=num / divider; /* the int will truncate the decimal part*/
printf( "%d\n ", digit );
num=digit%divider;
}
printf("\n");
Reply:// So all I did was put the numbers in an array
// to print out later in the correct order.
#include%26lt;stdio.h%26gt;
int main()
{
int num;
int digits[5];
int i = 4;
int j = 0;
printf("Enter your five-digit number\n");
scanf("%d", %26amp;num);
if(num %26lt; 10000 || num %26gt; 99999)
printf("%s", "Invalid number!\n");
else
{
while ( num %26gt; 0 %26amp;%26amp; i %26gt;= 0)
{
int digit = num % 10;
digits[i] = digit;
i--;
num = num / 10;
}
for( j = 0; j %26lt; 5; j++)
printf("%d ", digits[j]);
}
return 0;
}
Reply:int main(int argc, char **argv) {
int num;
int i;
/* If someone enters more than 100 digits you're screwed */
char numString[101];
printf("Enter your five-digit number\n");
scanf("%s", %26amp;numString);
for (i = 0; (i %26lt; strlen(numString)) %26amp;%26amp; (i %26lt; 5); ++i) {
num = atoi(numString[i]);
printf("%d ", num);
}
return 0;
}
This would do what you want but is not ideal and doesn't handle a few things...blah, blah, blah. You get the idea. Alternatively, you could do the following:
int main(int argc, char **argv) {
printf("Eat poop professor!!!\n");
return 0;
}
This one would DEFINITELY get you an A.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment