我正在为学校实验室在C中创建斐波那契序列生成器,但它不能成为0 1 1 2 3 5等常规方法......该程序应该是询问用户是否有限制,以及2个数字并从那里生成序列。
这是我到目前为止所做的:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int num1, num2, num3, limit;
int Fibarray[10];
//Ask the user for a limit to the number of values displayed, checks to see if value is greater
// than 10 or less than 0, if so displays an error message
printf("Please enter limit of values generated, the limit must be 10 or less, but greater than 0\n");
scanf ("%i", &limit);
if (limit > 10)
{
printf("Please enter a valid integer greater than 0, and less than or equal to 10");
}
else
printf("Please enter 2 numbers separated by a space, the second number must be larger than the first");
scanf ("%i", &num1, &num2);
if (num1>num2||num1<0)
{
puts("Please re enter your numbers, make sure they are in ascending order & the second number is greater than 0");
return(15);
}
else
{
// ...
}
}
我想弄清楚的是,我如何将这两个值加在一起,存储在数组中,然后再次添加到限制中。
我认为这个问题与How to generate Fibonacci series in C不同,因为在这个程序中我需要接受用户的值,而不是预设值。
我一直在查看我的书,但这不是很有用。
答案 0 :(得分:0)
关于:
scanf ("%i", &num1, &num2);
这将导致编译器输出警告消息,并且永远不会设置变量num2。建议:
size_t num1;
size_t num2;
....
if( 2 != scanf( "%lu %lu", &num1, &num2 ) )
{
fprintf( stderr, "scanf for num1, num2 failed\n" );
exit( EXIT_FAILURE );
}
答案 1 :(得分:0)
要打印序列,请执行以下步骤:
a
,即printf
c
计算为a
和b
的总和a = b
,b = c
。limit
次。关于您的代码,这是一个带有更严格的输入检查的改进版本:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int num1, num2, num3, limit;
//Ask the user for a limit to the number of values displayed, checks to see if value is greater
// than 10 or less than 0, if so displays an error message
printf("Please enter limit of values generated, the limit must be 10 or less, but greater than 0:\n");
if (scanf("%i", &limit) != 1 || limit <= 0 || limit > 10) {
printf("Please enter a valid integer greater than 0, and less than or equal to 10\n");
return 1;
}
printf("Please enter 2 numbers separated by a space, the second number must be larger than the first:\n");
if (scanf("%i%i", &num1, &num2) != 2 || num1 > num2) {
puts("Please re enter your numbers, make sure they are in ascending order\n");
return 2;
}
// ...
}