c ++中的循环,用于在计数可被4整除时跟踪

时间:2014-03-18 23:14:14

标签: c++

您好我的c ++程序有问题。基本上它是一个迭代用户想要它的次数的循环。现在,当它达到可被4整除的数字时,它会跟踪该数字,最后输出输入的数字可以被4整除的次数。

#include<iostream>
using namespace std;

int num;
int count;
int test = 0;

int main()
{
    cin>> num;
    for (int count = 0; count < num; count++)
        if (count % 4 == 0)
            (test++);
        else
            cout<<"";  

    return 0;
}

2 个答案:

答案 0 :(得分:1)

好吧 - 如果你在return中使用main,你的程序就会退出,因为这就是返回的作用 - 结束函数并返回一些值。如果您想实际打印 test的值,请在return之前执行此操作:

cout << test;
getch(); // use this so the console won't close automatically
return 0;

此外,整个程序可以写得更好:

int main()
{
    cin>> num;
    cout << num/4;
    getch(); // use this so the console won't close automatically
    return 0;
}

答案 1 :(得分:1)

需要使用循环吗?如果你只是需要&#34;一个给定的数字可以被4&#34;并且不需要循环

#include<iostream>
using namespace std;

int main()
{
    int num;
    cin>> num;
    cout<< num<<" is divisible by 4 "<< (num>>2) <<" time"<<(num>>2>1?"s":"") <<endl;
    return 0;
}

num>>2向右移位两次,这与将整数除以4相同。如果需要,可以用num/4替换。整数除法总是截断,所以对于所有正数,它就像向下舍入:你的循环给你的相同行为。