我有以下代码:
#include<stdio.h>
void main()
{
int a = -1, b = 1, c = 0, i, n, sum = 0 ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nThe fibonacci series is :") ;
for(i = 1 ; i <= n ; i++)
{
c = a + b ;
printf("%d-", c) ;
sum = sum + c ;
a = b ;
b = c ;
}
printf("\nThe sum of the fibonacci series is : %d", sum) ;
printf("\n");
}
现在我需要找到使总和大于7位的系列术语,我该怎么做?
P.S我是C
的新手,对不起我的英语。
答案 0 :(得分:1)
如果您想获得七位数的第一个总和,请将您的阈值设置为一百万,也称为1e6 = 10**6 = 1000000
。请注意,1000000
中有七位数字。
如果您希望总和超过七位数,请将阈值设置为一千万。这个数字有八位数。
以下代码可以解决问题。请注意,我们有一个for
循环而不是while
循环,它会在总和小于阈值的情况下继续迭代。
# include <stdio.h>
int main() {
int previous, current = 0, next = 1,
sum = current, threshold;
printf("Enter the threshold: ") ;
scanf("%d", &threshold) ;
printf("Fibonacci series: %d", current) ;
while (sum < threshold) {
previous = current;
current = next;
next = previous + current;
printf(" + %d", current) ;
sum += current;
}
printf(" = %d\n", sum);
return 0;
}
答案 1 :(得分:0)
#include<stdio.h>
void main()
{
int a = -1, b = 1, c = 0, i, n, term1, term2;
long sum = 0;
printf("Enter the limit : ");
scanf("%d", &n);
printf("\nThe fibonacci series is :");
for(i = 1 ; i <= n ; i++)
{
c = a + b ;
printf("%d \n", c) ;
sum = sum + c ;
if(sum >= 1000000){
term1 = a;
term2 = b;
break;
}
a = b ;
b = c ;
}
printf("\nThe sum of the fibonacci series is : %ld", sum);
printf("\n terms are %d and %d", term1, term2);
printf("\n");
}
当程序找到使得总和超过7位的正确术语时,它会从循环中断。 希望我理解你的意思。
答案 2 :(得分:0)
尽可能少地更改代码:
# include <stdio.h>
int main(int argc, char ** argv)
{
int a = -1, b = 1, c = 0, i = 1, n = 0, sum = 0 ;
printf("\nThe fibonacci series is :") ;
while (sum <= 10000000)
{
c = a + b ;
printf("%d-", c) ;
sum = sum + c ;
a = b ;
b = c ;
n = i;
i++;
}
printf("\nThe sum of the fibonacci series is : %d", sum) ;
printf("\nThe term is %d the value is %d", n , c);
printf("\n");
return 0;
}
答案 3 :(得分:-1)
您可以执行以下操作(您必须在顶部(第4行)声明number
和found = 0
):
if(sum >= 1000000 && !found) {
specialNumber = fibonacci;
found = 1;
}
因此它检查总和是否大于7位数!如果是,那么最后一个斐波那契数字就是你搜索的数字,这是使总和大于7位数的数字!并且发现只有第一个数字被分配给specialNumber。
所以你的程序看起来应该是这样的:
#include <stdio.h>
int main() {
int count, sum, specialNumber, fibonacci, numberOne, numberTow, found;
sum = 0, fibonacci = 0, numberOne = -1, numberTow = 1, found = 0;
int n;
printf("Enter the limit :\n>") ;
scanf("%d", &n) ;
printf("\nThe fibonacci series is :") ;
for(count = 1 ; count <= n ; count++) {
fibonacci = numberOne + numberTow;
printf("\n%d", fibonacci);
sum += fibonacci;
if(sum >= 1000000 && !found) {
specialNumber = fibonacci;
found = 1;
}
numberOne = numberTow;
numberTow = fibonacci;
}
printf("\nThe sum of the fibonacci series is : %d\n", sum);
printf("%d makes the sum bigger than 7 digits", specialNumber);
return 0;
}