C++测试代码

标签 c++

这是以二进制形式打印“c++”并同时测量时间的代码

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main(){
    unsigned int t = clock();
    string c = "c++";
    int t=0;
    for (int i=0;i<c.length();i++){
        t = (int) c[i];
        while (t!=0){
            cout << t % 2 <<endl;
            t >>= 1;
        }
    }
    unsigned int end = clock();
    cout << end-t << endl;
    return 0;
}

但是这里是错误的

1>------ Build started: Project: name_of_c++, Configuration: Debug Win32 ------
1>  c++_name.cpp
1>c:\users\david\documents\visual studio 2010\projects\name_of_c++\c++_name.cpp(11): error C2371: 't' : redefinition; different basic types
1>          c:\users\david\documents\visual studio 2010\projects\name_of_c++\c++_name.cpp(7) : see declaration of 't'
1>c:\users\david\documents\visual studio 2010\projects\name_of_c++\c++_name.cpp(12): warning C4018: '<' : signed/unsigned mismatch
1>c:\users\david\documents\visual studio 2010\projects\name_of_c++\c++_name.cpp(16): error C2059: syntax error : '>='
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

最佳答案

看这两行:

unsigned int t=clock();
int t=0;

它们都在同一个范围内,都定义了一个变量t。这在 C++ 中是不允许的!

如果您在解析错误消息时遇到问题,当您收到类似以下内容时:

c++_name.cpp(11): error C2371: 't' : redefinition; different basic types

括号中的数字 (11) 告诉您发生错误的行。

关于C++测试代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3223387/

相关文章:

c++ - 如何更改函数中的值或静态 char*? C++

c++ - 如何让69.99*100打印6999而不是6998?

c++ - 关于调用 srand 的说明

c++ - 检查循环中出现的任何条件是否已满足 C++

c++ - 内存有效的字符串 vector

C++ - 停止无限循环 - 追踪轮廓

c++ - 查找字节顺序指针类型转换的代码

c++ - 字符串的排列--error : no matching function for call to ‘std::set<char>::insert(std::string&)’

c++ - 在常量表达式中除以零

C++ less运算符使用转换运算符