簡體   English   中英

使用C編程的連續整數

[英]Sucessive integers using C programming

Example input: 20 10 5 20 2 20 20 20 2 2 0

Output:
(20*5)
(10*1)
(5*1)
(2*3)

我本學期剛剛開始編程,需要一個項目的幫助。 如果我的問題不清楚,我深表歉意。

因此,基本上我必須輸入正整數,直到輸入“ 0”將結束程序。 我不允許使用數組(無論如何)。

#include <stdio.h>


int main ()
{
int number, count=0

while(1)
{
    scanf("%d",&number);
    if (number!=0)
    {
        count++; continue;
    }
    else
    {
        printf("%d*%d",number,count);
        break;
    }
    return 0;
}

如何存儲這些多個數字,這樣我就不會與之前的數字重疊,並且每次輸入時都不會將重復的數字加1? 我不能向我的教授尋求幫助; 他只是告訴我用谷歌搜索。

“某個工程設備由連續數字(整數)的輸入控制。如果存在相同編號的運行,則該設備可以優化其性能。因此,我們希望對數據進行排列,以表明運行是編寫一個C程序,該程序讀取一個數字序列並以(n * m)的形式打印出每個數字游程,其中m是重復n次的數字。請注意,一個游程只能包含一個數字。數字以零結尾,這會使設備停止運行。”

該分配似乎基於行程編碼(RLE)的半熟知識。 無論如何,這是一個偽代碼,它可以執行所要求的操作。

in = read next number from input
current_num = in    // let the 1st number in list be current_num
count = 1

loop 
    in = read next number from input
    if (in == 0)  break   // we are done, get out of loop

    else if (in == current_num) count += 1

    else     // run has ended, print it and start new run
        print current_num * count
        current = in
        count = 1

end loop

print current_num * count    // we exited the loop before printing the last run
                              // so do it outside the loop

您可以在代碼中實現它,然后對其進行“優化”以除去重復的代碼,並注意一些特殊情況(例如“空”輸入,單數輸入等)。

編輯為了清楚起見,分配要求輸入“數字”,但示例輸出顯示“數字”。 這兩個是一樣的。

暫無
暫無

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

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