簡體   English   中英

如何總結C中的一行數字?

[英]How can I sum up the row of numbers in C?

所以我得到了一個任務來制作一個程序。 要創建的程序使用一個從數字 1 開始的變量。該變量的值每次迭代增加 1。 將之前和之后的迭代值相加。 在終端中顯示總和結果。 如果總和超過一百,程序將通過發出“程序完成”字樣退出迭代

我不理解這個任務,但我設法制作了這段代碼:

#include<stdio.h>
int main() {
    int i,j,rows;
    printf("Enter number of rows: ");
    scanf("%d", &rows);
    for (i=1; i<=rows; ++i) {
        for (j=1; j<=i; ++j)

        { printf("%d ",j); }
        printf("\n");
    }
    return 0;
}

我得到的問題:

  1. 我需要知道如果我將它們相加將是 100 的行數
  2. 我需要在輸出中顯示上一個方程,如下所示:

     1 = 1 1 + 2 = 3 1 + 2 + 3 = 6 1 + 2 + ... + etc = no more than 100

這是一些代碼的粗略草稿,可以執行您想要的操作。

#include <stdio.h>

int main()
{

int i,j,rows,sum;

printf("Enter number of rows: ");
scanf("%d", &rows);

for (i=1; i<=rows; i++) 
{
    sum = 0;

    for (j=1; j<=i; j++)
    { 
        sum += j;
        printf("%d ",j); 
    }


    printf(" : Sum = %i\n",sum);
    if(sum > 100)
    {
        printf("Program Complete\n");
        break;
    }
}

return 0;
}

樣本輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM