计算变量更改了多少次

Counting how many times variable has changed

本文关键字:多少次 变量 计算      更新时间:2023-10-16

我必须编写程序,当终止无限而循环"while(cin>>a)"时,假设"-1",程序告诉我值增加了多少倍。对于输入"0 0 2 2 3 4 8 8 8 8 -1",它应该打印"4"。第一部分不是问题,但我不知道如何计算它随着时间的推移发生了多少次变化。有什么提示吗?多谢。

您应该使用计数器,每次值增加时,计数器基本上都会增加。检查下面的代码:

int value, highestValue, counter = 0, counter2 = 0;
do{
       cout << "Enter the value: ";
       cin >> value;
       if(counter2 == 0){
                    highestValue = value;
                  }
       if(value > highestValue){
                  counter++;
                  highestValue = value;
                }
       counter2++;
}while(value != -1);
cout << "The number increased " << counter << " times!n";

第一个 if 语句中需要第二个计数器 (counter2) 来存储您输入的第一个值作为最大值。

int p = -1, k, a, b;
while( cin >> a )                                                //infinite loop
 { 
   if ( k != a )
      p++;
   b = a - k;
   if(a=-1)
    exit(0);
   k = a;
  }
cout << "value increased by" << b;
cout << "number of times it has changed over time = " << p;