while循环结束时n ++和++ n之间的区别? (ANSI C) [英] The difference between n++ and ++n at the end of a while loop? (ANSI C)

查看:307
本文介绍了while循环结束时n ++和++ n之间的区别? (ANSI C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但我无法弄清楚.它与n ++和++ n之间的差异有关(我以为我理解但显然不是).

this is probably a dumb question but I just can't figure it out. It has to do with the differences between n++ and ++n (which I thought I understood but apparently not).

#include <stdio.h>
#include <math.h>

long algorithmA(int n);
long algorithmB(int n);

int main(){
    long A, B;
    A = B = 0;
    int n = 1;
    while(A >= B){
        A = algorithmA(n);
        B = algorithmB(n);
        n++;
    }
    printf("At n = %d, Algorithm A performs in %ld seconds & "
           "Algorithm B performs in %ld seconds.", n, A, B);

}

long algorithmA(int n){
    return pow(n,4) * 86400 * 4;
}

long algorithmB(int n){
    return pow(3,n);
}

在这里您可能会告诉我,我想在什么时候看到算法A的性能优于算法B.功能和时间单位是在作业中给我的.

Here you can probably tell I'm trying to see at what point Algorithm A outperforms Algorithm B. The functions and units of time were given to me in a homework problem.

无论如何,我一直认为在while循环结束时"++"的顺序无关紧要.但是,如果我使用++ n而不是n ++,则会得到错误的答案.有人可以解释为什么吗?

Anyways, I always thought that the order of "++" would not matter at the end of a while loop. But if I put ++n instead of n++, I get the wrong answer. Can somebody explain why?

好吧,它在++ n中显示24,在n ++中显示25,但这一定是出于另一个原因.因为我现在才检查,所以没有区别.感谢您的耐心和时间,我只希望我知道自己做了什么!

Well it WAS showing 24 with ++n and 25 with n++, but it must have been for another reason. Because I just checked now and there is no difference. Thanks for your patience and time guys, I just wish I knew what I did!

推荐答案

n++++n之间的唯一区别是n++产生n的原始值,而++n产生的值. n递增后.两者都有通过增加n的值来修改它的副作用.

The only difference between n++ and ++n is that n++ yields the original value of n, and ++n yields the value of n after it's been incremented. Both have the side effect of modifying the value of n by incrementing it.

如果结果如代码中那样被丢弃,则没有有效的区别.

If the result is discarded, as it is in your code, there is no effective difference.

如果您的程序根据编写的内容而有所不同

If your program is behaving differently depending on whether you write

n++;

++n;

这一定是出于其他原因.

it must be for some other reason.

实际上,当我在系统上编译并执行程序时,在两种情况下我都得到完全相同的输出.在输出格式中添加换行符,我得到:

In fact, when I compile and execute your program on my system, I get exactly the same output in both cases. Adding newlines to the output format, I get:

At n = 25, Algorithm A performs in 114661785600 seconds &
Algorithm B performs in 282429536481 seconds.

您尚未告诉我们您要获得什么输出.请更新您的问题,以显示两种情况下的输出.

You haven't told us what output you're getting. Please update your question to show the output in both cases.

这篇关于while循环结束时n ++和++ n之间的区别? (ANSI C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆