一直在課堂上研究這個問題。不知道我做錯了什么。
好像我只是沒有正確的格式。我的教授希望輸出看起來像“5!=1 * 2* 3* 4* 5=120”
有人可以幫我弄這個嗎?以下是我到目前為止所擁有的:
#include <iostream>
#include <stdio.h>
int main() {
int n, i, fact;
printf("Enter a positive integer: \n");
scanf("%d", &n);
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for( i = 1; i <= n; i) {
fact *= i;
n= n * (n-1);
}
printf("Factorial of %d = ", &n, &fact) ;
}
return 0;
}
uj5u.com熱心網友回復:
#include <iostream>如果是C代碼則洗掉- 使用函式。
- 初始化區域變數(你沒有,這是未定義的行為)
- 使用 C 編譯器編譯 C 程式
unsigned long long fact(unsigned val, char *buff)
{
unsigned result = 1;
*buff = '1';
*buff = 0;
for(unsigned c = 2; c <= val; c )
{
buff = sprintf(buff, "x%u", c);
result *= c;
}
return result;
}
int main(void)
{
unsigned x;
char y[1000];
unsigned long long res;
if(scanf("%u", &x) == 1){res = fact(x, y); printf("factoral(%u) = %s = %llu\n", x, y, res);}
else printf("Invalid number!!!\n");
}
或沒有印刷步驟
unsigned long long fact(unsigned val)
{
unsigned result;
switch(val)
{
case 0:
case 1:
result = 1;
break;
case 2:
result = 2;
break;
default:
result = 2;
while(val > 2) result *= val--;
break;
}
return result;
}
int main(void)
{
unsigned x;
if(scanf("%u", &x) == 1) printf("factioral(%u) = %llu\n", x, fact(x));
else printf("Invalid number!!!\n");
}
https://godbolt.org/z/Tf5431zco
uj5u.com熱心網友回復:
對于初學者來說,將變數 n 宣告為有符號整數型別是沒有意義的。最好將其宣告為無符號整數型別。例如
unsigned int n, i, fact;
其次,變數 fact 沒有被初始化。您應該將其初始化為等于 1 的值。
所以上面的宣告可能看起來像
unsigned int n, i;
unsigned long long fact = 1;
在這個 for 回圈中
for( i = 1; i <= n; i) {
fact *= i;
n= n * (n-1);
}
該宣告
n= n * (n-1);
沒有意義,應洗掉。
在 printf 呼叫中,您必須使用變數的值而不是指向變數的指標,例如
printf("Factorial of %u = %llu\n", n, fact) ;
請注意<iostream>,您的程式中沒有使用頭檔案中的宣告,因此無論是 C 程式還是 C 程式,都請洗掉此頭檔案。
這是一個演示 C 程式。
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int fact = 1;
printf( "Enter a positive integer: " );
scanf( "%u", &n );
printf( "%u! = ", n );
for ( unsigned int i = 1; i <= n; i )
{
fact *= i;
if ( i != 1 ) printf( " * " );
printf( "%u", i );
}
printf( " = %llu\n", fact );
}
The program output might look like
Enter a positive integer: 5
5! = 1 * 2 * 3 * 4 * 5 = 120
If you are allowed to use only variables of the type int as you wrote in a comment to the answer then the program can look like
#include <stdio.h>
int main( void )
{
int n = 0;
int fact = 1;
printf( "Enter a positive integer: " );
scanf( "%d", &n );
if ( n < 0 )
{
puts( "Error! Factorial of a negative number doesn't exist.");
}
else
{
printf( "%d! = ", n );
for ( int i = 1; i <= n; i )
{
fact *= i;
if ( i != 1 ) printf( " * " );
printf( "%d", i );
}
printf( " = %d\n", fact );
}
}
To output multipliers in the reverse order like
5! = 5 * 4 * 3 * 2 * 1 = 120
rewrite the for loop the following way
for ( int i = n; i != 0; i-- )
{
fact *= i;
if ( i != n ) printf( " * " );
printf( "%d", i );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315516.html
上一篇:ReactNative[TypeError:undefinedisnotanobject(evaluating'iter[Symbol.iterator]')]錯誤
下一篇:使用函式編碼字串
