Objective c 将多个数据记录到单个变量中
问题:用户输入10位的数字,需要计算所有数字的总和 我试图键入变量“inta[10]={}”,但它不起作用,我可以在其中写入一些结果吗Objective c 将多个数据记录到单个变量中,objective-c,global-variables,Objective C,Global Variables,问题:用户输入10位的数字,需要计算所有数字的总和 我试图键入变量“inta[10]={}”,但它不起作用,我可以在其中写入一些结果吗 请编写示例代码。您没有指定使用哪种语言,所以我假设您使用的是java代码 为了满足您的要求,您必须做到以下几点: int number = 454685; // = an example number int[] arr = new int [6]; // array of int, 6 = digits of the number int i
请编写示例代码。您没有指定使用哪种语言,所以我假设您使用的是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
int number=454685;//=示例编号
int[]arr=新int[6];//整数数组,6=数字的位数
int i=0;//柜台
而(数量>0){
arr[i]=number%10;//将最后一位数字存储在arr[i]中
i++;//递增计数器
number=number/10;//每10除以一个数字以取消最后一个数字(已存储在arr[i]中)
}
整数和=0//声明sum变量
i=0//复位计数器
做{
总和=总和+arr[i];
i++;
}而(i
给您。是指
10位数的数字
,是吗?如果是,它是一个int
值,您不能直接在数组中存储单个数字。@user2520114然后看看这个问题和这个问题