【问题标题】:Record multiple data into a single variable将多个数据记录到单个变量中
【发布时间】:2013-06-25 13:06:56
【问题描述】:

问题:用户输入10位的数字,需要计算所有数字的总和。

我正在尝试键入变量“int a [10] = {}”,但它不起作用,我可以在其中写一些结果吗?

请写示例代码。

【问题讨论】:

  • 你的意思是number of 10-digits,是吗?如果是,它是一个int 值,您不能将单个数字直接存储在数组中。

标签: objective-c global-variables


【解决方案1】:

您没有指定您使用的是哪种语言,所以我回答您假设您正在使用 java 编码。

为了满足你的要求,你必须这样做:

int number = 454685; // = an example number
    int[] arr = new int [6]; // array of int, 6 = digits of the number
    int i = 0; // counter
    while (number > 0) {
        arr[i] = number % 10; //stores in arr[i] the last digit
        i++; //increment counter
        number = number / 10; //divides the number per 10 to cancel the last digit (already stored in arr[i])
    }
    int sum = 0; //declares the sum variable
    i = 0; //reset counter
    do{
        sum = sum + arr[i];
        i++;
    }while( i < arr.length); //this loop calculates the sum
    System.out.println(sum); //prints the sum of the digits

你来了。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 2020-12-26
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
相关资源
最近更新 更多