Reputation: 1
I am a beginner in c programming and I tried to write a program that asks for a number from 1 to 100 and tells then which numbers are equally divisible by 2 through 9. the point is I intended to show the result by 1 printf() and I wrote 8 %f and variable but some numbers have just 1 or 2 divisible not 8 !!!
int num;
float a2,a3,a4,a5,a6,a7,a8,a9,n2,n3,n4,n5,n6,n7,n8,n9;
float b2,b3,b4,b5,b6,b7,b8,b9;
printf("please enter an int number between 1 to 100 \n");
scanf(" %d", &num);
a2=( num % 2 == 0)?(b2=2):(n2);
a3=( num % 3 == 0)?(b3=3):(n3);
a4=( num % 4 == 0)?(b4=4):(n4);
a5=( num % 5 == 0)?(b5=5):(n5);
a6=( num % 6 == 0)?(b6=6):(n6);
a7=( num % 7 == 0)?(b7=7):(n7);
a8=( num % 8 == 0)?(b8=8):(n8);
a9=( num % 9 == 0)?(b9=9):(n9);
printf("your chosen number is divisible by %.0f %.0f %.0f %.0f %.0f %.0f %.0f %.0f ",b2,b3,b4,b5,b6,b7,b8,b9);
Upvotes: -1
Views: 72
Reputation: 3995
There are too many problems in your code:
You print the values of all b
even if the given number is not divisible by one of [2, 9]
What is the purpose of a
and n
?
You have not initialized b
. It can carry garbage values because of those conditions.
Why do you use floating point variables? Divisibility tests are for integers only.
Solution:
Instead of hardcoding a pattern, simply run a loop, and check and display the result simultaneously.
printf("%d is divisible by:", num);
for (int i = 2; i <= 9; ++i)
{
if (num % i == 0)
{
printf(" %d", i);
}
}
By the way, your code does not check if the given number is in your desired range as well.
Upvotes: 1