So I'm a beginner to programming and thought I would try and make a basic calculator that gives the sum or product of two numbers. However, in the while
loop of this program, the first printf
seems to print twice after the first iteration of the loop. Any help rectifying this would be greatly appreciated.
#include <stdio.h>
#include <string.h>
int multiply(int a, int b) {
return a * b;
}
void printMultiply(int x, int y) {
int result = multiply(x, y);
printf("\n%d\n", result);
}
int add(int a, int b) {
return a + b;
}
void printAdd(int x, int y) {
int result = add(x, y);
printf("\n%d\n", result);
}
int main() {
int product1 = 0;
int product2 = 0;
int sum1 = 0;
int sum2 = 0;
while (true) {
// this prints twice after first iteration?
printf("Would you like to add or multiply? (press a or m)\n");
char choice = ' ';
scanf("%c", &choice);
if (choice == 'm') {
printf("What two numbers would you like to multiply? (leave a space between numbers\n");
scanf("%d%d", &product1, &product2);
printMultiply(product1, product2);
} else
if (choice == 'a') {
printf("What two numbers would you like to add? (leave a space between numbers\n");
scanf("%d%d", &sum1, &sum2);
printAdd(sum1, sum2);
}
}
}