2016-11-07 82 views
-3

我的C程序不显示输出。C程序不能显示输出

我的C语言代码:

int x = 0; // Installment 
int y = 0 // Balance 

for (i=1; i<=installment;i++) 
     { 
      printf("%d %d %d\n", i, x=totalFee/installment, y = totalFee-(totalFee/instalment)); 
     } 

正确的输出:

 
Total fees: 300 
Month Installment Balance 
    1  100   200 
    2  100   100 
    3  100   0 

我的输出:

 
Total fees: 300 
Month Installment Balance 
    1  100   200 
    2  100   200 
    3  100   200 

这只是部分的代码。因为这是我有问题的部分。其他部分都很好。

+2

如果你使用C编程,为什么要添加C++标记? –

+0

@Someprogrammerdude男孩是我们同步。刚刚编辑它。 –

+1

也许你应该从当前的余额中扣除... –

回答

2

尝试这种情况:

for (i=1; i<=installment;i++) 
{ 
    x = totalFee/installment; 
    y = totalFee-x; 
    printf("%d %d %d\n", i, x, y); 
} 

在C/C++,编译器决定以何种顺序则计算参数当一个函数被调用。绝对不能保证订单将从第一个到最后一个参数。所以最有可能在x = totalFee/installment之前评估totalFee-x,这不是你所期望的。

参见Compilers and argument order of evaluation in C++Order of evaluation in C++ function parameters或甚至function parameter evaluation order。 特别是,检查this answer

现在您更新了您的帖子,并由y = totalFee-x替换为y = totalFee-(totalFee/instalment)。这最后一个应该作为y作业不依赖于x。如果它不适合你,那只是你以错误的方式做你的操作。使用调试器来查看发生了什么。

+0

兄弟, 感谢您的回复。 但是输出仍然与余额一样仍然不能扣除。 – Addison

+0

另外根据提问者的说法,他可能希望x = x * i在x初始化后插入。 – Nonanon

+0

其实我只是想我的“y”被扣除。感谢您的回复。 – Addison

1

该问题可能与功能参数的评估顺序有关。在y = totalFee-x之前,您无法知道或认为x=totalFee/installment已被执行。另外,在表达式中使用赋值通常是不好的做法。

尝试在循环主体更改为:

x = totalFee/installment; 
y = totalFee-x; 
printf("%d %d %d\n", i, x, y); 
0

也许你不`吨了解你的循环

突然想到一步到位呢。

首先, I = 1,X =3分之300= 100,Y = 300 - 100 = 200

其次, 设为i = 2,X =3分之300= 100,Y = 300 - 100 = 200

第三, I = 2,X =3分之300= 100,Y = 300 - 100 = 200

你做X这100

+0

你不能假定循环是这样执行的。 – Lundin

+0

行..非常感谢 – Addison

0

程序为您所需的输出

for (i=1; i<=installment;i++) 
{ 
    x = totalFee/installment; 
    y = totalFee-(x * i); 
    printf("%d %d %d\n", i, x, y); 
} 
+0

感谢您的所有帮助..我真的很感激它。愿上帝保佑你们。 – Addison