Reputation: 6298
I have to multiply digits by taking input from the user and when he enter 'n' it will produce the answer.
For example (2*3*2 = 12). But I manage to write the code for taking two inputs but can't find the way to take multiple inputs from user and produce the total answer. Here is the code;
void main (void)
{
float f1,f2;
float total;
int status1,status2;
printf("Enter first number to multiply:'n' to quit.\n ");
status1=scanf("%f",&f1);
printf("Enter another number to be multiply:'n' to quit.\n ");
status2=scanf("%f",&f2);
while (status1==1 && status2==1)
{
total=f1*f2;
status1=scanf("%1.0f",&f1);
status2=scanf("%1.0f",&f2);
}
printf("Multiplition Total = %1.0f",total);
getch();
}
Upvotes: 0
Views: 4895
Reputation: 122001
This would do what you need and handles, 0, 1 or an unlimited number of inputs:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
float f1;
float total = 0;
printf("Enter number: ");
if (scanf("%f",&total))
{
for (;;)
{
printf("Enter number: ");
if (!scanf("%f", &f1))
{
break;
}
total *= f1;
}
}
printf("Multiplication Total = %f\n",total);
getch();
return 0;
}
It keeps a running total as values are entered but it stops on first invalid input, not just when n
is entered.
Upvotes: 0
Reputation: 19847
Tested:
#include <stdio.h>
int main()
{
int total = 1, factor = 1, success;
do
{
total *= factor;
printf("Enter integer number to multiply or 'n' to quit: ");
success = scanf("%d", &factor);
}
while (success);
printf("Multiplication Total = %d\n", total);
return 0;
}
And a piece of advice as you said you start your adventure with C:
Unless you have some specific reason to do otherwise, use double, not float.
However, in your question you asked for digits (integer) multiplication, so int is sufficient. If you can avoid floating point numbers, avoid them. They're much more complicated then integers and can let you in worse problems if you don't use them with caution.
You can refer to What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Upvotes: 1
Reputation: 30805
You can use a while loop, as follows.
float prod = 1, f;
printf( "Enter the numbers, n to stop.\n" );
while( scanf( "%f", &f ) )
prod *= f;
printf( "product = %f\n", prod );
Upvotes: 1
Reputation: 25599
Untested:
float f, p = 1;
printf ("Enter a number: ");
fflush (stdout);
while (scanf("%f", &f) != EOF)
{
p *= f;
printf ("Enter another number: ");
fflush (stdout);
}
printf ("Product: %f\n", p);
Upvotes: 0