我已经用C编写了一个程序,它使用switch语句计算并显示上周售出的产品1至5的总零售价值。如果用户输入1到5以外的数字,系统会提示他们:“不存在此类产品,请输入有效的产品编号。”但是,如果他们输入两位数字(如77),则会显示此提示两次。如果他们输入一个两位数字如36,则显示一次。下面是代码:C程序开关不能正常工作
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <math.h>
unsigned int switchfn(); // prototype function for the switch statement
// initialize global variables
unsigned int productOne = 0;
unsigned int productTwo = 0;
unsigned int productThree = 0;
unsigned int productFour = 0;
unsigned int productFive = 0;
// program execution
int main(void)
{
// retail price of each product
double product1 = 2.98;
double product2 = 4.50;
double product3 = 9.98;
double product4 = 4.49;
double product5 = 6.87;
// user enters data for each product on each day
puts("Enter the product number");
puts("Enter the quantity sold for Monday");
unsigned int monday = switchfn();
puts("Enter the the product number and quantity sold for Tuesday:");
unsigned int tuesday = switchfn();
puts("Enter the the product number and quantity sold for Wednesday:");
unsigned int wednesday = switchfn();
puts("Enter the the product number and quantity sold for Thursday:");
unsigned int thursday = switchfn();
puts("Enter the the product number and quantity sold for Friday:");
unsigned int friday = switchfn();
puts("Enter the the product number and quantity sold for Saturday:");
unsigned int saturday = switchfn();
puts("Enter the the product number and quantity sold for Sunday:");
unsigned int sunday = switchfn();
// display total amount of each product sold last week
puts("\nThe total amount of each product sold is:");
printf("Product 1: %u\n", productOne);
printf("Product 2: %u\n", productTwo);
printf("Product 3: %u\n", productThree);
printf("Product 4: %u\n", productFour);
printf("Product 5: %u\n\n", productFive);
// display total retail cost for each product sold
puts("\nThe total dollar amount for each product sold is:");
printf("Product 1: %.2f\n", productOne * product1);
printf("Product 2: %.2f\n", productTwo * product2);
printf("Product 3: %.2f\n", productThree * product3);
printf("Product 4: %.2f\n", productFour * product4);
printf("Product 5: %.2f\n\n", productFive * product5);
system("pause");
return 0;
} // end of program
// switch function
unsigned int switchfn()
{
int productNumber; // product 1 through 5
// only while product 1 through 5 is being entered.
while ((productNumber = getchar()) != EOF) {
switch (productNumber) {
case '1':
++productOne;
break;
case '2':
++productTwo;
break;
case '3':
++productThree;
break;
case '4':
++productFour;
break;
case '5':
++productFive;
break;
case '\n':
case '\t':
case ' ':
break;
default:
printf("%s", "No such product exists.");
puts(" Please enter a valid product number.");
break;
}
}
return 0;
}
这会涉及知道一个两位数,以及用于这种方式的任何数量大于9是一个单数而不是把每个数字作为输入?如果是这样,我将如何实现这一点?任何帮助是极大的赞赏!
张贴的代码是由数字读出值的数字,更好读取整个号码,或许通过'如果(1!= scanf的( “%d”,&productNumber)){//处理错误}' – user3629249
通过使用函数重构代码以消除复制粘贴也是_highly_ recommended, – 9000