上一篇已经搭建好了开发环境并成功运行了案例,这一篇将会自己创建一个项目并运行。
新建一个项目,名称可以为Bell,如图,官方文档没有注意一点,要确保选择.NET Framwork 4.6.1,否则会编译报错。
新建成功后会看到一个cs文件和qs文件,把qs文件重命名为Bell.qs,内容写改为如下:
namespace Quantum.Bell
{
open Microsoft.Quantum.Primitive;
open Microsoft.Quantum.Canon;
operation Set (desired: Result, q1: Qubit) : ()
{
body
{
let current = M(q1);
if (desired != current)
{
X(q1);
}
}
}
operation BellTest (count : Int, initial: Result) : (Int,Int)
{
body
{
mutable numOnes = 0;
using (qubits = Qubit[1])
{
for (test in 1..count)
{
Set (initial, qubits[0]);
let res = M (qubits[0]);
// Count the number of ones we saw:
if (res == One)
{
set numOnes = numOnes + 1;
}
}
Set(Zero, qubits[0]);
}
// Return number of times we saw a |0> and number of times we saw a |1>
return (count-numOnes, numOnes);
}
}
}
cs文件修改如下:
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace Quantum.Bell
{
class Driver
{
static void Main(string[] args)
{
using (var sim = new QuantumSimulator())
{
// Try initial values
Result[] initials = new Result[] { Result.Zero, Result.One };
foreach (Result initial in initials)
{
var res = BellTest.Run(sim, 1000, initial).Result;
var (numZeros, numOnes) = res;
System.Console.WriteLine(
$"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4}");
}
}
System.Console.WriteLine("Press any key to continue...");
System.Console.ReadKey();
}
}
}
会看到在BellTest位置显示波浪线有错误,可能是预览版的原因,无需理会,F5编译运行通过即可。成功会显示如下:
Init:Zero 0s=1000 1s=0
Init:One 0s=0 1s=1000
Press any key to continue...
参考链接:https://docs.microsoft.com/en-us/quantum/quantum-writeaquantumprogram?view=qsharp-preview