Latest web development tutorials

C Exercise Example 18

100 cases of classic C language 100 cases of classic C language

Title: Demand s = a + aa + aaa + aaaa + aa ... a value, where a is a number. For example, 2 + 22 + 222 + 2222 + 22222 (In this case the sum total of the number 5), a few numbers together with a keyboard control.

Program Analysis: The key is to calculate the value of each item.

Source Code:

//  Created by www.w3big.com on 15/11/9.
//  Copyright © 2015年 本教程. All rights reserved.
//

#include<stdio.h>
int main()
{
    int s=0,a,n,t;
    printf("请输入 a 和 n:\n");
    scanf("a=%d,n=%d",&a,&n);
    t=a;
    while(n>0)
    {
        s+=t;
        a=a*10;
        t+=a;
        n--;
    }
    printf("a+aa+...=%d\n",s);
    return 0;
}

The above example output is:

请输入 a 和 n:
a=2,n=5
a+aa+...=24690

100 cases of classic C language 100 cases of classic C language