Too*_*his 2 c scope loops while-loop cs50
我最初尝试使用Do While循环但是与while循环具有相同的结果.用户必须输入数字28-31.在第一次尝试时,如果用户正确输入值,它将转到代码的下一部分.但是,如果用户输入的值不正确,它将再次询问一个号码,但无论他们输入什么,它都会不断重复.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
printf("Days in month: ");
int daysInMonth = GetInt();
while (daysInMonth < 28 || daysInMonth > 31)
{
printf("Days in month: ");
int daysInMonth = GetInt();
printf("%i\n", daysInMonth);
}
printf("Pennies on the first day: ");
int pennies = GetInt();
while (pennies < 1)
{
printf("Pennies on the first day: ");
int pennies = GetInt();
}
}
Run Code Online (Sandbox Code Playgroud)
printf语句用于调试目的,以测试是否daysInMonth重新分配值.
Kir*_*rov 13
在第一个while,你有:
int daysInMonth = GetInt();
Run Code Online (Sandbox Code Playgroud)
这定义了一个新的变量daysInMonth,该变量while是本体的本地变量,它隐藏了具有相同名称的外部变量.所以,在循环的条件下while,你使用外部daysInMonth,在体内,你使用内部daysInMonth.
我想你想int从这一行中删除部分,只需修改外部daysInMonth.
实际上,在第二个while循环中你有相同的情况.