我对编程完全陌生,我目前正在参加编程课程。我需要调整以下代码以允许未指定数量的正整数。我已经看了这个,似乎没有正确的平均值。请帮忙。谢谢。
#include <stdio.h>
int main ()
{
/* variable definition: */
int count, value, sum;
double avg;
/* Initialize variables */
count = 0;
sum = 0;
avg = 0.0;
// Loop through to input values
while (count < 20)
{
printf("Enter a positive Integer\n");
scanf("%d", &value);
if (value >= 0) {
sum = sum + value;
count = count + 1;
}
else {
printf("Value must be positive\n");
}
}
// Calculate avg. Need to type cast since two integers will yield an
// integer
avg = (double) sum/count;
printf("average is %lf\n ", avg );
return 0;
}
答案 0 :(得分:1)
您可以使用无限循环并检查负值和 for(;;)
{
printf("Enter a positive Integer\n");
if(scanf("%d", &value) == 1 )
{
if (value >= 0) {
sum = sum + value;
count = count + 1;
}
else {
printf("Value must be positive\n");
break;
}
}
else
{
break;
}
}
的返回结果作为中断条件。
示例代码如下:
int count = 0, value = 0, sum = 0;
double avg = 0;
此外,您的初始化代码是可以的,但可以通过这种方式更清洁(不需要在声明和初始化之间分开 - 您可以将它们分成一行):
function getGroups{
$Groups += Get-ADGroup -Filter * -SearchBase "ou=Groups,ou=DCM,ou=NTG,dc=prod,dc=main,dc=ntgov" | Select-Object -ExpandProperty samaccountname
return $Groups
}
Measure-Command{
$Groups = getGroups
write-host "Groups:" $Groups.Count
}
Measure-Command{
$date = $(get-date).ToString("dd MMM yyyy")
$global:FileName = "Active Directory Group Membership - DCM -" + $date
$stringBuilder = New-Object System.Text.StringBuilder
foreach ($GroupName in $Groups){
Get-ADGroupMember -Identity $GroupName | Sort-Object $_.SamAccountName | ForEach-Object {
$ParentGroupName = (Get-ADGroup -Identity $GroupName).SamAccountName
$MemberName = $_.SamAccountName # Member of the Group.
if ($_.ObjectClass -eq 'group') {
$DisplayName = ' - '
} elseif ($_.ObjectClass -eq 'user') {
$a = (Get-ADUser -Identity $MemberName -Properties Displayname)
$DisplayName = $a.DisplayName
}
$null = $stringBuilder.Append("$ParentGroupName, $MemberName, $DisplayName")
}
}
outputArray = $stringBuilder.ToString()
out-file C:\Users\augut\Desktop\$FileName.csv
outputArray | out-file C:\Users\augut\Desktop\$FileName.csv
}