我想撰寫一個程式來計算前n個自然數的總和
我試過的代碼:
#include<stdio.h>
void main()
{
int sum=0,i=1,n;
printf("Enter the number upto where you want to print add : ");
scanf("%d",&n);
printf("\nSUM = ");
while(i<=n)
{
if(i<n)
{
printf("%d ",i);
}
if(i=n)
{
printf("%d",i);
}
sum=sum i;
i ;
}
printf("\nThe sum of the first %d numbers is : %d",n,sum);
return 0;
}
預期輸出是如果 n=5
Enter the number upto where you wnat to print add :
sum =1 2 3 4 5
The sum of the first %d numbers is : 5
但我得到的是
sum=1 5
and the value is 5
但是當我使用if else而不是 two 時if它的作業
uj5u.com熱心網友回復:
問題是你的 if 陳述句:
if(i=n)
單個 = 是一個賦值;你想要的是與 == 的比較,所以:
if(i==n)
uj5u.com熱心網友回復:
您在 if 陳述句中使用了 i=n 而不是 i==n 。
uj5u.com熱心網友回復:
您在此 if 陳述句的運算式中使用賦值運算子=而不是比較運算子==
if(i=n)
{
printf("%d",i);
}
你需要寫
if( i == n)
{
printf("%d",i);
}
此外,最好使用 for 回圈而不是 while 回圈。
例如
for ( int i = 0; i < n; )
{
printf( i == n ? "%d" : "%d ", i );
sum = i;
}
該變數i僅在回圈中使用。所以它應該在使用它的范圍內宣告。
始終嘗試在使用它們的最小范圍內宣告變數。這將使您的程式更具可讀性。
注意,根據 C 標準,沒有引數的函式 main 應宣告為
int main( void )
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378667.html
上一篇:接收資料流的UART同步演算法
下一篇:計算最終訂單/編程的價值
