我不知道如何从用户那里获得一个数字,然后输出一个输出,说明所有可能的完美平方,直到程序达到给定的数字。
我们在C中使用循环,我们必须使用for循环来获取数字并输出可能的完美平方。
以下是输出应该是什么的示例:输入一个介于1和1000之间(包括1和1000(的数字:-50您输入的数字-50不在1到1000之间。请重新输入介于1和1000之间(包括1和1000(的数字:100
介于1和100之间(包括1和100(的完美正方形为:1.4.9162536496481100
我的代码:
int main(void)
{
// Constant and Variable Declarations
const int MIN_NUM = 1; // constant for the minNum allowed
const int MAX_NUM = 1000; // constant for the maxNum allowed
int userNum = 0; // input variable
int userNum1 = userNum;
int perfectSquare = 0;
// *** Your program goes here ***
printf("Enter a number between 1 and 1000 inclusive: "); // asking the user to input their number
scanf("%d", &userNum);
// validation
while (userNum < MIN_NUM || userNum > MAX_NUM) {
printf(" The number you entered, %d, was not between 1 and 1000.n", userNum); // telling user num they entered was not valid
printf(" Please re-enter a number between 1 and 1000 inclusive: "); // asking the user to enter a different number
scanf("%d", &userNum);
}
printf("n"); // blank line
// output
printf("The perfect squares between 1 and 100 inclusive are:");
printf("n");
return 0;
} // end main()
不知道如何找到完美的方形很抱歉,如果这些都不清楚,这是我第一次在overflow上发帖!感谢的所有帮助
您可以做的一件事是,不必检查哪些小于userNum
的数字是完美正方形,而是从1开始打印每个完美正方形,直到找到一个大于userNum
的数字。这可以通过for循环轻松完成。
(代码本身留给读者练习(
感谢大家的帮助!
int main(void)
{
// Constant and Variable Declarations
const int MIN_NUM = 1; // constant for the minNum allowed
const int MAX_NUM = 1000; // constant for the maxNum allowed
int userNum = 0; // input variable
int userNum1 = userNum;
int perfectSquare = 0;
int root1 = 0;
int root2 = 0;
// *** Your program goes here ***
printf("Enter a number between 1 and 1000 inclusive: "); // asking the user to input their number
scanf("%d", &userNum);
// validation
while (userNum < MIN_NUM || userNum > MAX_NUM) {
printf(" The number you entered, %d, was not between 1 and 1000.n", userNum); // telling user num they entered was not valid
printf(" Please re-enter a number between 1 and 1000 inclusive: "); // asking the user to enter a different number
scanf("%d", &userNum);
}
printf("n"); // blank line
// output
printf("The perfect squares between %d and %d inclusive are:n", MIN_NUM, userNum);
for (int i = 1; perfectSquare <= userNum - 1; i++) {
root1 = sqrt(floor(userNum));
root2 = sqrt(userNum);
perfectSquare = i * i;
printf("%dn", perfectSquare);
if (perfectSquare > userNum) {
break;
}
}
printf("n");
return 0;
} // end main()
输出:
Enter a number between 1 and 1000 inclusive: 81
The perfect squares between 1 and 81 inclusive are:
1
4
9
16
25
36
49
64
81