2017-11-06 11 views
-4

整数をこのように一緒に追加する方法を教えてください。数式ではなくCで整数を加算する

1で始まり、次に2を追加します。したがって、12を持ちます。次に3を追加すると、123があります。

私はただ連結しますが、私はこのプログラムで文字列を使用することはできません。

+2

、文字列と文字列の連結への変換?あなたは 'sprintf'について聞いたことがありますか? – ShadowRanger

+6

あなたの記述は小数点以下の数字のように見えます。その仕組みが分かっていますか?数字に「10」を掛ければ何が起こるか知っていますか?今それについてしばらく考えてみてください。 –

+0

整数の配列を作る? 追加する桁数の最大値がわかっている場合は、配列に順番に配置できます。 –

答えて

0

このようにしますか?

コード:追加の所望の変化を作るために(十進法のメカニズムに基づいて)いくつかの異常な数学を使用

#include <stdio.h> 

int main() { 
    int a = 4, b = 5, c = 6, d = 7; 
    printf("a+b=%d\n",a*10+b); 
    printf("a+b+c=%d\n",(a*10+b)*10+c); 
    printf("a+b+c+d=%d\n",((a*10+b)*10+c)*10+d); 
    return 0; 
} 
4

#include <stdio.h> 

int main(void) 
{ 
    int i; 
    int number=0; 
    for (i=1; i<5; ++i) 
    { 
     number=number*10 + i; 
     printf("%d\n", number); 
    } 
    return 0; 
} 

を出力:

1 
12 
123 
1234 
-1

これは典型的な使用例ですrealloc

char *mystr = NULL; 
char *temp; 
char c, ch; 

short count = 0; 
do { 
    printf("Enter character : "); 
    scanf(" %c", &c); // Better use sscanf or fgets, scanf is problematic 
    temp = (char*)realloc(mystr, (++count) * sizeof *mystr); 
    if (NULL != temp) { 
     mystr = temp; 
     mystr[count - 1] = c; 
    } 
    printf("Do you wish to continue: "); 
    scanf(" %c", &ch); 
} while ('y' == ch); 
// Since and since you don't have a null terminated string, do 
for (int i = 0; i < count; i++) 
    printf("%c", mystr[i]); 

    printf("\n"); 
free(mystr); // Freeing the memory 
getch(); 

注:そして、あなたは、このプログラム内の文字列を持っていない;)だから、

+0

フォーマットとして使用される文字列以外に、このプログラムに文字列を持たない: ''文字入力: "、"%c "、...' – chux

+1

注: 'for(int i = 0; i ' printf( "。* s \ n"、count、mystr); ' – chux

関連する問題