我正在创建一个程序,要求用户选择他们想要的品牌水以及他们想要送到家中的瓶子数量。程序使用while循环询问用户他们想要的瓶子数量是否正确,如果不是,循环将允许重新输入他们想要的数量。
每次我必须选择一个新的水品牌时,该计划一直有效;它以前坚持以前水品牌的细节。我无法在程序中看到while循环的问题。这是代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int valuechange = 0;
int correct = 0;
int choice = 0;
int numofbottles;
while (choice != 6)
{
printf("1. Buxton\n");
printf("2. Evian\n");
printf("3. Harrogate\n");
printf("4. Power life\n");
printf("5. Smart water\n");
printf("6. Exit\n\n");
printf("Enter your choice here: ");
scanf("%d", &choice);
/*each if statement has a while loop for if the user wants to re-enter a value of water bottles*/
if (choice == 1)
{
while (correct != 1)
{
printf("Please choose how many bottles of Buxton you want to be delivered to your house:\n\n");
scanf("%d", &numofbottles);
printf("you have chosen %d bottles, is this the correct amount?\n(enter 1 for yes or 2 for no):\n\n", numofbottles);
scanf("%d", &correct);
}
printf("Thank you, your order for %d Buxton bottles will be delivered to you\nwithin 3 working days.\n\n", numofbottles);
}
if (choice == 2)
{
while (correct != 1)
{
printf("Please choose how many Evian bottles you want to be delivered to your house:\n\n");
scanf("%d", &numofbottles);
printf("you have chosen %d bottles, is this the correct amount?\n(enter 1 for yes or 2 for no):\n\n", numofbottles);
scanf("%d", &correct);
}
printf("Thank you, your order for %d Evian bottles will be delivered to you\nwithin 3 working days.\n\n", numofbottles);
}
if (choice == 3)
{
while (correct != 1)
{
printf("Please choose how many Harrogate bottles you want to be delivered to your house:\n");
scanf("%d", &numofbottles);
printf("you have chosen %d bottles, is this the correct amount?\n(enter 1 for yes or 2 for no):\n\n", numofbottles);
scanf("%d", &correct);
}
printf("Thankyou, your order for %d Harrogate bottles will be deliver to you\nwithin 3 working days.\n\n", numofbottles);
}
if (choice == 4)
{
while (correct != 1)
{
printf("Please choose how many Powerlife bottles you want to be delivered to your house:\n\n");
scanf("%d", &numofbottles);
printf("you have chosen %d bottles, is this the correct amount?\n(enter 1 for yes of 2 for no):\n\n", numofbottles);
scanf("%d", &correct);
}
printf("Thankyou, your order for %d Powerlife bottles will be deliver to you\nwithin 3 working days.\n\n", numofbottles);
}
if (choice == 5)
{
while (correct != 1)
{
printf("Please choose how many Smart water bottles you want to be delivered to your house:\n\n");
scanf("%d", &numofbottles);
printf("you have chosen %d bottles, is this the correct amount?\n(enter 1 for yes or 2 for no):\n\n", numofbottles);
scanf("%d", &correct);
}
printf("Thankyou, your order for %d Smart water bottles will be deliver to you\nwithin 3 working days.\n\n", numofbottles);
}
}
return 0;
}
答案 0 :(得分:2)
一次迭代后,您不会重置correct
。每次将其设置为0
:
while (choice != 6)
{
correct = 0;
...
/*rest of the code */
}
顺便说一下,你有很多代码重复。您只需使用数组来存储瓶子类型并在循环中使用数组元素。