上周我有一个来自我老师的项目,要求我开发一个程序,该程序接收一个字符串(精确的整数流)并计算字符串中每个数字的字符串中的数字总和即。< / p>
如果输入是31456
我确实提交了一个工作项目,但它充满了意大利面条代码(嵌套循环,如果字符串长度小于循环数,则结束),这不是一个干净的方法。在这种情况下,我很想知道并研究了很多东西。如果没有C语言中的嵌套for循环,我还没有找到任何方法(或者我放弃了太快?)
同样,我不是要求你们回答我的问题,而是想知道是否有一种方法可以在没有嵌套循环的情况下这样做(如果输入的长度和嵌套循环的数量会有问题)。
答案 0 :(得分:3)
这是我的建议:停止思考“循环”并开始思考“步骤”。如果输入字符串包含n
个字符,则表示您有n+1
个步骤。
现在,思考以下三个问题:
k
的解决方案,您如何计算步骤k+1
的解决方案?由于这是作业,我会让你从这里开始。
答案 1 :(得分:0)
如果我让你正确
double temp = 0;
for(int i = 0; i < str.Length; i++) // str is your complete number
{
temp += Convert.ToDouble(str[i]);
}
希望它有所帮助。
答案 2 :(得分:0)
伪代码:
array of sums
sums[0] = 0; // That first time that you want to get 0!!
for i = 1 to length of str
sums[i] <- sums[i-1] + str[i]
答案 3 :(得分:0)
#include <stdio.h>
int sum(const char ch){
static int sum = 0;
int retValue = sum;
sum += ch -'0';
return retValue;
}
int main(){
char nums[] = "314156";/* "31456" ? */
int size = sizeof(nums)/sizeof(char);
int i;
for(i=0 ; i< size ; ++i){
printf("%d time loop sum is %d\n", i+1, sum(nums[i]));
}
return 0;
}
<强>样本强>
1 time loop sum is 0
2 time loop sum is 3
3 time loop sum is 4
4 time loop sum is 8
5 time loop sum is 9
6 time loop sum is 14
7 time loop sum is 20
答案 4 :(得分:0)
有一个名为partial_sum()
的C ++标准库函数,它执行您在输入中一次传递中描述的一系列总和。
int sums[] = { 0, 3, 1, 4, 1, 5, 6 };
std::partial_sum(sums, sums + 7, sums);
// The results are left in sums[0]..sums[6]
答案 5 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void printResults(int* results,int size);
int main( int argc, char** argv ){
char nums[] = "314156";/* "31456" ? */
int i,tmp;
char tmpc[2];
int length=strlen(nums);
#define LENGTH length
int results[LENGTH];
results[0]=0;
tmpc[0]=nums[0];
sscanf(tmpc, "%d", &tmp);
results[1]=tmp;
int result=results[1];
for(i=2 ; i< length ; ++i){
tmpc[0]=nums[i];
sscanf(tmpc, "%d", &tmp);
result+=tmp;
results[i]=result;
}
printResults(results,length);
return 0;
}
static void printResults(int* results,int size){
int i;
for(i=0;i<size;i++){
printf("%d time loop sum is %d\n", i+1,results[i]);
}
}
对于初学者来说,这是用C语言编写的非常基本且易于理解的代码,输出是:
答案 6 :(得分:-1)
#include<iostream>
#include<cctype>
using namespace std;
void main()
{
const int SIZE=10;
char myArray[SIZE];
int length=0,sum=0;
cout<<"enter Array of digit from 1-9\n\n ";
cin>>myArray;
cout<<myArray<<endl;
for(int i=0;i<myArray[i];i++)
{
if(!isspace(myArray[i]))
//if(myArray[i]!=NULL)
length++;
}
cout<<length<<endl;
for(int i=0;i<length;i++)
{
sum+=myArray[i]-'0';
}
cout<<sum;
}