Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                                                                                            
                
        
我正在尝试使用if else语句编写一个基本的计算器程序,但是有问题。加法和乘法功能有效,而减法和除法功能无效。
如何编写可以找到n个数字的减法和除法的C程序?





#include<stdio.h>
int main()
{
int n, m, i, d;
float sum;
printf("Enter the number what you want to calculate\n");
printf("1.) Addition\n2.) subtraction\n3.) multiplication\n4.) Division\n");
scanf("%d", &n);
if (n == 1) {
printf("\nyou select addition\n");
printf("enter how many number you want to add\n");
scanf("%d", &m);
sum = 0;
for (i = 0; i < m; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%d", &d);
sum += d;
}
printf("your answer is %f", sum);
}
else if (n == 2) {
printf("\nyou select Subtraction\n");
printf("enter how many number you want to Subtract\n");
scanf("%d", &m);
sum = 0;
for (i = 0; i < m; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%d", &d);
sum -= d;
}
printf("your answer is %f", sum);
}
else if (n == 3) {
printf("\nyou select Multiplication\n");
printf("enter how many number you want to Multiply\n");
scanf("%d", &m);
sum = 1;
for (i = 0; i < m; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%d", &d);
sum = sum * d;
}
printf("your answer is %f", sum);
}
else if (n == 4) {
printf("\nyou select Division\n");
 printf("enter how many number you want to divide\n");
scanf("%d", &m);
sum = 1;
for (i = 0; i < m; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%d", &d);
sum /= d;
}
printf("your answer is %f", sum);
}
else
printf("you Enter wrong number");
return 0;
}

最佳答案

你快到了。我认为您只是为sumsum2的初始值而苦苦挣扎。

保留sum进行加/减(需要初始化为0),保留sum2进行乘法/除法(需要初始化为1)。

float sum = 0;
float sum2 = 1.;


然后加法变成

sum += numbers[i]


减成

sum -= numbers[i]


乘法变成

sum2 *= numbers[i]


和分裂成为

sum2 /= numbers[i]


并确保正确订购printfscanf和数学运算。

关于c - 如何编写可以找到n个数字的除法和减法的C程序? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51985176/

10-11 22:53