我在将此作业问题转换为伪代码时遇到了一些麻烦。我想知道逻辑是否正确。
问题:
编写一个打印以下元素的程序:1,3,5,7,9,11,13,15,17,19,直到用户输入的值。该程序每行不应打印超过10个数字。打印的最后一行可能小于10.除了第一个数字和最后一个数字之外,应该有一个“,”分隔所有数字。每行上的最后一个数字后面应该有一个“。”。在退出之前,它还应打印所有元素的总和:计算项目的总和并输入结果。例如,如果用户输入76,则输出应如下所示 程序的示例运行应如下:
输入您的号码(> = 1和< = 100):76 你的序列是
1,3,5,7,9,11,13,15,17,19。 21,23,25,27,29,31,33,35,37,39。 41,43,45,47,49,51,53,55,57,59。 61,63,65,67,69,71,73,75。
上述元素的总和1444。
我的尝试:
Algorithm ElementsSequenceSeries
// declare variables
Var num, count, odd, sum, arrayOne, arrayTwo, arrayThree, arrayFour, arrayFive
// initialize variables
Count = 0; sum = 0; odd=0; arrayOne = 0; arrayTwo = 0; arrayThree = 0; arrayFour = 0; arrayFive = 0;
<BeginAlg>
Print (Input 1<= num <= 100);
Count = count + 1;
Odd = (count*2)–1; // create a list of odd numbers up to a user-defined value less than 100
If (num > odd)
Print(Odd);
// For the indices 0 to 8, place a comma after each element of the array.
For (num <=20 and num> odd) and (arrayOne[9]= {0,1,2,3,4,5,6,7,8})
Print (arrayOne[]= {0,1,2,3,4,5,6,7,8} + “,”);
EndFor
// For the index 9, place a fullstop after it.
For (num <=20 && num> odd) and (array One[]= 9)
Print arrayOne[]= 9 + “.”)
EndFor
For (num <=40 and num> odd) and (arrayTwo[]= {0,1,2,3,4,5,6,7,8})
Print (arrayTwo[]= {0,1,2,3,4,5,6,7,8} + “,”);
EndFor
For (num <=40 and num> odd) and (arrayTwo[]= 9)
Print arrayTwo[]= 9 + “.”)
EndFor
For (num <=60 and num> odd) and (arrayThree[]={0,1,2,3,4,5,6,7,8})
Print (arrayThree[]= {0,1,2,3,4,5,6,7,8} + “,”);
EndFor
For (num <=60 and num> odd) and (arrayThree[]= 9)
Print arrayThree[]= 9 + “.”)
EndFor
For (num <=80 and num> odd) and (arrayFour[]={0,1,2,3,4,5,6,7,8})
Print (arrayFour []= {0,1,2,3,4,5,6,7,8} + “,”);
EndFor
For (num <=80 and num> odd) and (arrayFour []= 9)
Print arrayFour []= 9 + “.”)
EndFor
For (num <=100 and num> odd) and (arrayFive[]={0,1,2,3,4,5,6,7,8})
Print (arrayFive []= {0,1,2,3,4,5,6,7,8} + “,”);
EndFor
For (num <=100 and num> odd) and (arrayFive []= length)
Print arrayFive []= length + “.”);
EndFor
EndIf
Sum = arrayOne, arrayTwo, arrayThree, arrayFour, arrayFive;
Print(sum);
<EndAlg>
答案 0 :(得分:1)
您提出的算法使用可以保存的内存,因为我们需要打印所有奇数整数,可以使用四个变量解决问题,一个用于跟踪总和,一个用于更改行,一个用于用户输入和一个作为循环变量。
Variables:
sum :int // keeps track of the sum
count :int // keeps track of the Integer printed in a line.
i :int // looping variable.
n :int // Given as input
Algorithm:
/* BEGIN ALGORITHM */
n=input();
count=0;
sum=0
for(i=1:i<n:i=i+2){
print("i,");
count=count+1;
if(count>9){
print("/n"); // change line;
count=0;
}
sum=sum+i;
}
print("n.");
print("Sum is (sum+n)");
/* END ALGORITHM */