gpt4 book ai didi

c - 为什么我的阶乘程序在 C 中返回 0?

转载 作者:行者123 更新时间:2023-11-30 21:02:36 26 4
gpt4 key购买 nike

所以我正在用 C 编写我的第一个程序,我正在尝试编写一个阶乘函数,但它似乎不起作用,我不知道为什么。

#include <stdio.h>

int x = 5;
int counter;

int factorial (int x)
{
int counter = 1;

for ( x > 0; x<= 100;)
counter = counter * x;

x = x - 1;
}

int main (int factorial)
{
printf ("%i", counter);
}

所以是的,不知道为什么这不起作用?任何帮助:)

最佳答案

更新答案

//int x = 5; this isn't doing anything
//int counter; not doing anything

int factorial(int x)
{
int counter = 1;
/*
for (x > 0; x <= 100;)
counter = counter * x;
1) x is input, don't use as counter, not in this case anyway
2) The variable 'counter' is where x is supposed to be
3) the loop is infinite
*/

x = 1; //initialize x
for (counter = 1; counter <= x; counter++)
x = x * counter;

//x = x - 1; shouldn't be here

//x has to be returned
return x;
}

//int main(int factorial) //don't put random arguments in main
int main()
{
//call the function
printf("%i", factorial( 5 ));
return 0;
}

关于c - 为什么我的阶乘程序在 C 中返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29023807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com