所以,基本上我需要询问用户他想要添加多少个数字,然后让他输入数字,但我不知道如何添加数字而不将它们存储在同一个变量中,或者如何要添加相同的变量但具有不同的值,这在pascal中非常容易,但我不知道如何在C中执行此操作。
到目前为止,这是我的代码......
int main(int argc, char *argv[]) {
int i, n, age;
printf("How many numbers do you want to add?\n");
scanf("%d", &n);
for (i = 1; i <= n; i = i++) {
printf("type in the number:\n");
scanf("%d", &age);
}
return 0;
}
答案 0 :(得分:2)
#include <stdio.h>
int main(){
int n ,age,sum = 0;
printf("How many numbers do you want to enter\n");
scanf("%d",&n);
while (n > 0) {
printf("Enter the age");
scanf("%d",&age);
sum += age;
n--;
}
printf("%d",sum);
return 0;
}
这是需要少一个变量的例子。
答案 1 :(得分:2)
要计算输入数字的总和,您可以为总和定义一个变量,并在输入时添加每个数字。
请注意,您的代码中存在未定义的行为:i = i++;
您不能同时具有副作用并修改同一表达式中的i
,除非存在序列点,否则您不太可能在初学者的代码中找到。只需i++
即可增加i
。
以下是修复和完成代码的方法:
#include <stdio.h>
int main(int argc, char *argv[]) {
int i, n, age, total = 0;
printf("How many numbers do you want to add?\n");
if (scanf("%d", &n) == 1) {
for (i = 0; i < n; i++) {
printf("type in the number:\n");
if (scanf("%d", &age) != 1)
break;
total = total + age;
}
printf("the sum is %d\n", total);
}
return 0;
}
答案 2 :(得分:0)
int main(){
int i,n ,age,sum=0;
printf("How many numbers do you want to enter\n");
scanf("%d",&n);
for(i = 1;i<=n;i++){
printf("Enter the age");
scanf("%d",&age);
sum+=age;
}
printf("%d\n",sum);
return;
}
答案 3 :(得分:0)
使用数组。
int age[100];
并在你的for循环中,将所有年龄存储在该数组中。
scanf("%d",&age[i]);
答案 4 :(得分:0)
我相信这是您寻找的最佳方式:
#include <stdio.h>
int main()
{
int n;
printf("how many numbers do you want to add?\n");
scanf("%d", &n);
if (n <= 0)
{
printf("Error\n");
getchar();
return 0;
}
int age[n];
for (int i = 0; i < n; i++)
{
printf("type in a number:\n");
scanf("%d", &age[i]);
while (age[i] <= 0)
{
printf("Insert a positive number:\n");
scanf("%d", &age[i]);
}
}
}
答案 5 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
int main(){
int i,n,sum=0;
int *age;
fflush(stdin);
printf("How many numbers do you want to enter: ");
scanf("%d",&n);
printf("\n");
age = (int*) malloc (sizeof(int)*n);
if(age == NULL)
return -1;
for(i = 0; i < n; i++){
printf("Enter the age: ");
scanf("%d",&age[i]);
}
printf("\n");
for(i = 0; i < n; i++)
printf("Age[%d] %d\n",i, age[i]);
/*Finally free the memory here*/`
free(age);
return 0;
}
答案 6 :(得分:0)
<ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Multiple,
InstanceContextMode:=InstanceContextMode.PerSession,
UseSynchronizationContext:=False,TransactionIsolationLevel:=System.Transactions.IsolationLevel.Serializable,
TransactionTimeout:="00:00:30",
ReleaseServiceInstanceOnTransactionComplete:=False,
TransactionAutoCompleteOnSessionClose:=True
)>
Public Class RechnungInternalWS
Implements IRechnungInternalWS
<OperationBehavior(TransactionScopeRequired:=True,
TransactionAutoComplete:=True)>
Public Function PdfVerarbeitungLoslegen(idAusGeplanteRechnungen As
Integer, LettershopDrucken As Boolean) As RechnungPDFOriginal Implements
IRechnungInternalWS.PdfVerarbeitungLoslegen
' do something
End Function
End Class